ListView Context Menu - java

I am working with ContextMenu on my ListView. The problem I'm facing is I'm not getting ContextMenu on item that is already selected in ListView since it is not touchable at all.

call this inside onCreate():
registerForContextMenu(lv);
And to access the selected item during long click:
#Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
if (v.getId() == R.id.lv) {
ListView lv = (ListView) v;
AdapterView.AdapterContextMenuInfo acmi = (AdapterContextMenuInfo) menuInfo;
YourObject obj = (YourObject) lv.getItemAtPosition(acmi.position);
menu.add("One");
menu.add("Two");
menu.add("Three");
menu.add(obj.name);
}
}

Resolved!
What I did is "android:focusable="false" for all the buttons inside my ListView item, they were stealing the focus making selected list item non-touchable.
Reference: click-events-listview-gridview

Related

I need to use a list Fragment and adapter to pass and update string data in the form of a to-do list

I am a fairly novice android programmer and I need some help in regards to the use of a List fragmnet.
To begin:
I currently have three main components in my simple To-do List application.
The first is a Main activity that impliments a custom method I made that simply updates the arraylist through the array Adapepter I have made within it.
public class ToDoListActivity extends ActionBarActivity implements OnNewItemAddedListener{public void newItemAdded(String newItem)
{
todoItems.add(newItem);
arrayAdapter.notifyDataSetChanged();
}
public ArrayAdapter<String> arrayAdapter;
public ArrayList<String> todoItems;
#Override
protected void onCreate (Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
//Inflate the root view
setContentView(R.layout.to_do_list_activity);
//Get references to the fragments
FragmentManager fragmentManager = getFragmentManager();
ToDoListFragment toDoListFragment = (ToDoListFragment)
fragmentManager.findFragmentById(R.id.ToDoListFragment);
//Create the array list of to do items
todoItems = new ArrayList<>();
//Create the array adapter to bind the array to the listView
arrayAdapter = new ArrayAdapter<>(this,
android.R.layout.simple_list_item_1, todoItems);
//Bind the array adapter to the listView
toDoListFragment.setListAdapter(arrayAdapter);
}
#Override
public boolean onCreateOptionsMenu (Menu menu)
{
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_to_do_list, menu);
return true;
}
#Override
public boolean onOptionsItemSelected (MenuItem item)
{
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//no inspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
I Also have an edit text fragment that handles the input of text that would be the To-do items. The newItem variable that is fed through the onNewItemListner() method is populated using my edit text fragment.
`public class EditTextFragment extends Fragment{
//This variable stores a reference to the parent ToDoListActivity that implements
//this interface.
#Override
public View onCreateView (LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState)
{
//set the key listener on the edit text view on the UI. This handles the taps on the
//Edit text box on the UI
//inflate the view from the XML file
View view = inflater.inflate(R.layout.edit_text_fragment, container, false);
//Create the edit text variable where the reference to the UI XML file is
final EditText myEditText = (EditText)view.findViewById(R.id.myEditText);
//Set a key listener on the edit text field
myEditText.setOnKeyListener(new View.OnKeyListener() {
public boolean onKey(View v, int keyCode, KeyEvent event)
{
if (event.getAction() == KeyEvent.ACTION_DOWN)
{
if ((keyCode == KeyEvent.KEYCODE_DPAD_CENTER) ||
(keyCode == KeyEvent.KEYCODE_ENTER)) {
String newItem = myEditText.getText().toString();
ToDoListActivity onItemAddedListener = new ToDoListActivity();
onItemAddedListener.newItemAdded(newItem);
myEditText.setText("");
return true;
}
}
return false;
}
});
return view;
}
public void onAttach(ToDoListActivity activity)
{
super.onAttach(activity);
}
}`
Finally I have a List fragment.
public class ToDoListFragment extends ListFragment{
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState){
//Inflate the XML UI component for the
View view = inflater.inflate(R.layout.to_do_list_fragment, container, false);
return view;
}
public void onAttach(ToDoListActivity activity)
{
super.onAttach(activity);
}
}
Now the problem I am running into is a null point exception. on the todoitems (arraylist) and the arrayAdapeter. They are for whatever reason not being instantiated. SO I can't pass any strings from my edit text field to them without crashing the app. I need to get them working and I would also like to use the list fragment to do so. Any help would be greatly appriciated. Any more information can be provided if needed.
Thank you.
Probably your edit text fragment have no access to the ArrayList or ArrayAdapter. I can't really tell without seeing its code.
As I see you have your fragments embedded in activity's layout and accessing them by ID.
The fragments are useful if you want to have parts of your UI dynamically loaded/unloaded. If you are planning to have just ListView and edit text on the screen then probably you can do it without fragments. It would be much easier. Just put a regular ListView and EditText in your activity's layout.
Actually the ListFragment is a Fragment that hosts a ListView.

non empty ListView giving error of Invalid index 0, size is 0

I have a ListView fragment in which I have registered the ListView for a context menu:
CourseArrayAdapter adapter = new CourseArrayAdapter(getActivity(), register.getCourseListByGrade(grade));
setListAdapter(adapter);
getListView().setLongClickable(true);
registerForContextMenu(getListView());
I am confident that my adapter contains a non-empty list because it the ListView is populated with my custom views.
Context menu related methods:
#Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
MenuInflater inflater = getActivity().getMenuInflater();
inflater.inflate(R.menu.menu_course_context, menu);
AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo)menuInfo;
menu.setHeaderTitle(((CourseArrayAdapter)getListAdapter()).getItem(info.position).getCourseName());
}
#Override
public boolean onContextItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.action_remove:
register.removeCourse(((CourseArrayAdapter) getListAdapter()).getItem(((AdapterView.AdapterContextMenuInfo) item.getMenuInfo()).position).getId());
return true;
case R.id.action_edit:
register.editCourse(((CourseArrayAdapter) getListAdapter()).getItem(((AdapterView.AdapterContextMenuInfo) item.getMenuInfo()).position).getId());
return true;
}
return super.onContextItemSelected(item);
}
Calling getListAdapter().getItem(info.position) in onCreatedContextMenu works without error and shows the correct menu title. However upon clicking on option the following error is displayed:
08-14 16:02:46.964 1923-1923/com.andhruv.schoolapp E/MessageQueue-JNIļ¹• java.lang.IndexOutOfBoundsException: Invalid index 0, size is 0
at java.util.ArrayList.throwIndexOutOfBoundsException(ArrayList.java:255)
at java.util.ArrayList.get(ArrayList.java:308)
at android.widget.ArrayAdapter.getItem(ArrayAdapter.java:337)
at com.andhruv.schoolapp.CourseListFragment.onContextItemSelected(CourseListFragment.java:62)
at android.support.v4.app.Fragment.performContextItemSelected(Fragment.java:1912)
CourseListFragment.java:62 is the line
register.editCourse(((CourseArrayAdapter) getListAdapter()).getItem(((AdapterView.AdapterContextMenuInfo) item.getMenuInfo()).position).getId());
CourseArrayAdapter:
class CourseArrayAdapter extends ArrayAdapter<Course> {
private Gpa gpaCalculator;
public CourseArrayAdapter(Context context, List<Course> values) {
super(context, 0,values);
gpaCalculator = new Gpa();
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = (LayoutInflater)getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View rowView = inflater.inflate(R.layout.item_course,parent,false);
TextView textViewCourseName = (TextView)rowView.findViewById(R.id.textViewCourseName);
TextView textViewGpa = (TextView)rowView.findViewById(R.id.textViewGpa);
TextView textViewGrade = (TextView)rowView.findViewById(R.id.textViewGrade);
TextView textViewType = (TextView)rowView.findViewById(R.id.textViewType);
TextView textViewCategory = (TextView)rowView.findViewById(R.id.textViewCategory);
textViewCourseName.setText(getItem(position).getCourseName());
textViewGpa.setText(String.valueOf(gpaCalculator.calcCourseVal(getItem(position).getLetterGrade(),getItem(position).getCourseLevel(),true)));
textViewType.setText(String.valueOf(getItem(position).getCourseLevel()));
textViewCategory.setText(String.valueOf(getItem(position).getCategory()).replace('_',' '));
textViewGrade.setText(String.valueOf(getItem(position).getLetterGrade()));
textViewCourseName.setTag(getItem(position).getId());
return rowView;
}
}
Why does the call ((CourseArrayAdapter)getListAdapter()).getItem(info.position) work in onCreateContextMenu but not in onContextItemSelected?
I suspect you're not modifying the adapter correctly in code of:
register.removeCourse(((CourseArrayAdapter) getListAdapter()).getItem(((AdapterView.AdapterContextMenuInfo) item.getMenuInfo()).position).getId());
OR
register.editCourse(...
It is hard for me to suggest a complete code fix for this since your code does not fit into my coding style and of course I don't know your code well. However I am providing sample code to remove items from the adapter. Basically if you want to add, remove, or edit data from your collection of List<Course>, you need to notify the adapter.
Sample code:
adapter = getListAdapter();
adapter.remove(adapter.getItem(position));
adapter.notifyDataSetChanged();
I hope that's clear enough for you to get a good start.

how to highlight the selected item in the menu on the navigation bar drawer

i already created a navigation drawer bar with a menu but i want to highlight and disable the selected item on the menu bar when i check the drawer bar.
how can i do that ?
also i did not see the click animation when i click the item on the menu
please help
Thanks.
this is the code i used
mRecyclerView.addOnItemTouchListener(new RecyclerView.OnItemTouchListener() {
#Override
public boolean onInterceptTouchEvent(RecyclerView recyclerView, MotionEvent motionEvent) {
View child = recyclerView.findChildViewUnder(motionEvent.getX(),motionEvent.getY());
if(child!=null && mGestureDetector.onTouchEvent(motionEvent)){
Drawer.closeDrawers();
Toast.makeText(MainActivity.this, "The Item Clicked is: " + recyclerView.getChildPosition(child), Toast.LENGTH_SHORT).show();
int pos = recyclerView.getChildPosition(child);
if(pos== 1){
Intent intent = new Intent(getApplicationContext(),About.class);
startActivity(intent);
}
return true;
}
return false;
}
#Override
public void onTouchEvent(RecyclerView recyclerView, MotionEvent motionEvent) {
}
#Override
public void onRequestDisallowInterceptTouchEvent(boolean disallowIntercept) {
}
});
RecyclerView does not handle item selection or states like a ListView does. Instead you have to handle this manually in your view holder.
The first thing you can do is declare your item view as clickable, in your `ViewHolder constructor :
public ViewHolder(View itemView) {
super(itemView);
// Make this view clickable
itemView.setClickable(true);
// ...
}
http://www.grokkingandroid.com/statelistdrawables-for-recyclerview-selection/

Android Dragging ListView and ContextMenu

I'm still working with dragging listview (example from google https://www.youtube.com/watch?v=_BZIvjMgH-Q) - long click by listview item - goes dragging and I want to implement context menu on short click, but my changes do not seem towork. After short click on listview item goes dragging effect..
here is my code for activity:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Utils.changeTheme(this,getApplicationContext());
Utils.setLang(this,getApplicationContext());
setContentView(R.layout.activity_list);
listView = (DynamicListView) findViewById(R.id.listview);
adapter = new StableArrayAdapter(this, R.layout.text_view, productsArray);
listView.setList(productsArray);
listView.setAdapter(adapter);
listView.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
registerForContextMenu(listView);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
view.showContextMenu();
}
});
}
With simple listview, short click working without any problems...
Could anybody explain what I'm doing wrong?
Thx in advance!
The best solution in this case is use popup menu instead of context menu.

Detect the GridView item selected in the method onContextItemSelected

I have a GridView with an ArrayAdapter and I'd like to detect the context item selection and show a "Delete" option for deleting the object selected. I fill the grid with imageviews correctly only need the detect the delete petition. My Code:
ArrayList<MyClass> array;
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.maingrid);
array=Manager.getMyArray();
GridView gridview = (GridView) findViewById(R.id.gridview);
gridview.setAdapter(new mArrayAdapter(this,array) );
registerForContextMenu(gridview);
}
#Override
public void onCreateContextMenu(ContextMenu menu, View v,
ContextMenuInfo menuInfo) {
menu.add(0, DELETE_ID, 0 , R.string.delete);
}
#Override
public boolean onContextItemSelected(MenuItem item) {
switch(item.getItemId()) {
case DELETE_ID:
return true;
}
return super.onContextItemSelected(item);
}
How can I guess whats the element of the array I have to remove? Thanks
In onContextItemSelected try this:
AdapterContextMenuInfo info = (AdapterContextMenuInfo) item.getMenuInfo();
you can get the selected item like this:
youradapter.getItem((int)info.id))
override the getItem() function in the adapter to return the selected item..

Categories