I'm creating a simple dialog with a ListView on it. I want to be able to access a context menu on it. Here's the basic code I've:
final Dialog dialog = new Dialog(context);
dialog.setContentView(R.layout.activity_lista);
dialog.setTitle("Contact");
ListView lv = (ListView) dialog.findViewById(R.id.listView); Cursor cursor = db.readData();
String[] from = new String[]{DatabaseHandler.KEY_contacts, DatabaseHandler.KEY_number};
int[] to = new int[]{R.id.contacts, R.id.number};
#SuppressWarnings("deprecation")
final
SimpleCursorAdapter adapter = new SimpleCursorAdapter(Home.this, R.layout.show, cursor, from, to);
adapter.notifyDataSetChanged();
lv.setAdapter(adapter);
registerForContextMenu(lv);
here the method onCreateContextMenu:
#Override
public void onCreateContextMenu(ContextMenu menu, View v,ContextMenu.ContextMenuInfo menuInfo) {
super.onCreateContextMenu(menu, v, menuInfo);
getMenuInflater().inflate(R.menu.menu_context, menu);
}
And finally I override the onContextItemSelected:
#Override
public boolean onContextItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.call:
Toast.makeText(this,"call" ,Toast.LENGTH_LONG).show();
return true;
case R.id.sms:
Toast.makeText(this,"sms" ,Toast.LENGTH_LONG).show();
return true;
case R.id.delete:
Toast.makeText(this,"delete" ,Toast.LENGTH_LONG).show();
return true;
default:
return super.onContextItemSelected(item);
}
}
I've tried also to override setOnMenuItemClickListener() inside onContextItemSelected()
but my problem still is not solved :( Any help?
You can get Item using this method
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Object listItem = lv.getItemAtPosition(position);
}
});
Related
I am looking for a way to have a Snackbox pop up at the bottom of the display when the user deletes an item from the database using the caseR.id.delete:. Below I have attached code from the fragment. If you need more of my code from different areas, please let me know.
/**
* A simple {#link Fragment} subclass.
*/
public class MainActivityListFragment extends ListFragment {
private ArrayList<Note> notes;
private NoteAdapter noteAdapter;
#Override
public void onActivityCreated(Bundle savedInstanceState){
super.onActivityCreated(savedInstanceState);
/*
String[] values = new String[] {"Android", "iPhone", "Windows", "WebOS", "Android", "iPhone", "Windows", "WebOS" };
ArrayAdapter<String> adapter = new ArrayAdapter<String>(getActivity(), android.R.layout.simple_list_item_1, values);
setListAdapter(adapter);
*/
NotesDbAdapter dbAdapter = new NotesDbAdapter(getActivity().getBaseContext());
dbAdapter.open();
notes = dbAdapter.getAllNotes();
dbAdapter.close();
noteAdapter = new NoteAdapter(getActivity(), notes);
setListAdapter(noteAdapter);
getListView().setDivider(null);
getListView().setDividerHeight(0);
registerForContextMenu(getListView());
}
#Override
public void onListItemClick(ListView l, View v, int position, long id){
super.onListItemClick(l, v, position, id);
launchNoteDetailActivity(MainActivity.FragmentToLaunch.VIEW, position);
}
#Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo){
super.onCreateContextMenu(menu, v, menuInfo);
MenuInflater menuInflater = getActivity().getMenuInflater();
menuInflater.inflate(R.menu.long_press_menu, menu);
}
#Override
public boolean onContextItemSelected(MenuItem item){
AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo) item.getMenuInfo();
int rowPosition = info.position;
Note note = (Note) getListAdapter().getItem(rowPosition);
switch (item.getItemId()){
case R.id.edit:
launchNoteDetailActivity(MainActivity.FragmentToLaunch.EDIT, rowPosition);
Log.d("menu clicks", "we pressed edit");
return true;
case R.id.delete:
NotesDbAdapter dbAdapter = new NotesDbAdapter(getActivity().getBaseContext());
dbAdapter.open();
dbAdapter.deleteNote(note.getId());
notes.clear();
notes.addAll(dbAdapter.getAllNotes());
noteAdapter.notifyDataSetChanged();
dbAdapter.close();
}
return super.onContextItemSelected(item);
}
private void launchNoteDetailActivity(MainActivity.FragmentToLaunch ftl, int position){
Note note = (Note) getListAdapter().getItem(position);
Intent intent = new Intent(getActivity(), NoteDetailActivity.class);
intent.putExtra(MainActivity.NOTE_TITLE_EXTRA, note.getTitle());
intent.putExtra(MainActivity.NOTE_MESSAGE_EXTRA, note.getMessage());
intent.putExtra(MainActivity.NOTE_CATEGORY_EXTRA, note.getCategory());
intent.putExtra(MainActivity.NOTE_DATE_EXTRA, note.getDate());
intent.putExtra(MainActivity.NOTE_ID_EXTRA, note.getId());
switch(ftl){
case VIEW:
intent.putExtra(MainActivity.NOTE_FRAGMENT_TO_LOAD_EXTRA, MainActivity.FragmentToLaunch.VIEW);
break;
case EDIT:
intent.putExtra(MainActivity.NOTE_FRAGMENT_TO_LOAD_EXTRA, MainActivity.FragmentToLaunch.EDIT);
}
startActivity(intent);
}
}
In your build.gradle add latest design library.
compile 'com.android.support:design:X.X.X' // where X.X.X version
And then, in your fragment do:
Snackbar
.make(view, "Item deleted",Snackbar.LENGTH_SHORT)
.show();
The parameter view could be the fragment's root layout. You just need it's reference.
For more information see http://www.materialdoc.com/snackbar/
Add design Lib
Compile 'com.android.support:design:X.X.X'
Code:
case R.id.delete:
NotesDbAdapter dbAdapter = new NotesDbAdapter(getActivity().getBaseContext());
dbAdapter.open();
dbAdapter.deleteNote(note.getId());
notes.clear();
notes.addAll(dbAdapter.getAllNotes());
noteAdapter.notifyDataSetChanged();
dbAdapter.close();
// Show SNACK Bar
mRoot = (RelativeLayout) view.findViewById(R.id.mainrl);
Snackbar snackbar = Snackbar.make(mRoot , "Item Deleted", Snackbar.LENGTH_LONG);
snackbar.show();
here mRoot is your main root layout of your fragment.
I have the following code, which runs when I click on my list, but I need it to only pop up a menu when I long click, the short click does other things.
#Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
super.onCreateContextMenu(menu, v, menuInfo);
if (v.getId()==R.id.listView1) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.menu_list, menu);
}
}
#Override
public boolean onContextItemSelected(MenuItem item) {
AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo) item.getMenuInfo();
switch(item.getItemId()) {
case R.id.add:
// add stuff here
CreateWO.performClick();
return true;
case R.id.punchin:
final Country country = (Country) ListView1.getItemAtPosition(getwoindex());
punchin.performClick();
Toast.makeText(getApplicationContext(), "Work Order="+country.code, Toast.LENGTH_SHORT).show();
return true;
case R.id.punchout:
punchout.performClick();
return true;
default:
return super.onContextItemSelected(item);
}
}
For normal click on listView item use: listView.onItemClickListener and for long click use: listView.setOnItemLongClickListener as follows:
ListView lv =(ListView)findViewById(R.id.my_list);
----
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
//Do something
}
});
lv.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
//do something on long click
//like show contextMenu
return false;
}
});
EDIT:
For ContextMenu:
You can either call openContextMenu(view) in your onItemLongClick (as above) OR you can use registerForContextMenu(view), for example:
lv.setAdapter(adapter);
registerForContextMenu(lv);
By default contextMenu will open when a user long clicks your view. In this case you do not need to call onLongClick manually on the listView.
I have used the following code to set context menu for my listview. Now I want to create the onContextItemClickListener for that context menu. Apparently there no such method like listview.setOnContextItemClickListener. Kindly Help me out here.
ListView listView = new ListView(getApplicationContext());
#SuppressWarnings("unchecked")
ArrayAdapter listViewArrayAdapter = new ArrayAdapter(getApplicationContext(),
android.R.layout.simple_list_item_1, locations);
listView.setAdapter(listViewArrayAdapter);
listView.setFocusableInTouchMode(true);
listView.setOnFocusChangeListener(
new View.OnFocusChangeListener() {
#Override
public void onFocusChange(View arg0, boolean arg1) {
Log.i("SampleApp", "onFocusChanged() - view=" + arg0);
}
});
listView.setOnItemClickListener( new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView adapterView, View view,
int arg2, long arg3) {
int selectedPosition = adapterView.getSelectedItemPosition();
Log.i("SampleApp", "Click on position"+selectedPosition);
}
});
listView.setOnCreateContextMenuListener(
new View.OnCreateContextMenuListener() {
public void onCreateContextMenu(ContextMenu menu, View view,
ContextMenu.ContextMenuInfo menuInfo) {
AdapterContextMenuInfo mi = (AdapterContextMenuInfo) menuInfo;
menu.add(0, 0, 0, "Delete");
}
});
You should add:
// we register for the contextmneu
registerForContextMenu(lv);
to register for context menu (i.e lv is the instance of ListView) and then:
// This method is called when user selects an Item in the Context menu
#Override
public boolean onContextItemSelected(MenuItem item) {
int itemId = item.getItemId();
// do your logic here
return true;
}
Hope this is what you are looking for.
PS: If you are interested i wrote a post about it, give a look here
I have an list view that displays an id name description etc... i created a context menu to use on that list and i want to get the name of a specific row through the context menu. How can i do this
ListAdapter adapter = new SimpleAdapter(
AllProductsActivity.this, productsList,
R.layout.list_item, new String[] { TAG_ID,
TAG_NAME, TAG_DATA, TAG_DATA2, TAG_QTD},
new int[] { R.id.id, R.id.descricao, R.id.data, R.id.data2, R.id.qtd});
// updating listview
setListAdapter(adapter);
}
});
}
}
#Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo){
getMenuInflater().inflate(R.menu.context, menu);
}
public boolean onContextItemSelected(MenuItem item) {
AdapterContextMenuInfo info = (AdapterContextMenuInfo) item.getMenuInfo();
switch(item.getItemId()) {
case R.id.item1:
long id = getListAdapter().getItemId(info.position);
Toast.makeText(getApplicationContext(),String.valueOf(id),
Toast.LENGTH_SHORT).show();
return true;
case R.id.item2:
return true;
default:
return super.onContextItemSelected(item);
}
}
}
You should use a custom list adapter.
Then you can use an onItemClickListener to get the clicked item and so the name etc...
Here is an tutorial for a custom adapter:
http://theopentutorials.com/tutorials/android/listview/android-custom-listview-with-image-and-text-using-baseadapter/
You want to register for context menu like: registerForContextMenu(yourListView).
I've been trying to create a clickable listview that takes in a string array and a few images and presents them in a textview style. So far I have managed to create a listview with each of the strings and images, however I am unsure how to use the onClick method so as to make the textviews clickable to start new activities etc.
Here is my code so far (Excluding XML):
public class MySimpleArrayAdapter extends ArrayAdapter<String> {
private final Context context;
private final String[] values;
public MySimpleArrayAdapter(Context context, String[] values) {
super(context, R.layout.activity_test2, values);
this.context = context;
this.values = values;
}
/* Print a toast when a list item is clicked, don't know what to do */
public void onClick() {
switch (list item) {
case 0:
Toast.makeText(this.context, "Pressed!", Toast.LENGTH_LONG).show()
break;
}
case 1:
etc....
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View rowView = inflater.inflate(R.layout.activity_test2, parent, false);
TextView textView = (TextView) rowView.findViewById(R.id.label);
ImageView imageView = (ImageView) rowView.findViewById(R.id.icon);
textView.setText(values[position]);
String s = values[position];
if (s.startsWith("Report a Road Delay")) {
imageView.setImageResource(R.drawable.ic_menu_compose);
} else if (s.startsWith("View Reported Delays")) {
imageView.setImageResource(R.drawable.ic_menu_view);
} else if (s.startsWith("Search a Road for Delays")) {
imageView.setImageResource(R.drawable.ic_menu_search);
} else if (s.startsWith("Update a Delay Report")) {
imageView.setImageResource(R.drawable.ic_menu_edit);
} else if (s.startsWith("Validate a Delay Report")) {
imageView.setImageResource(R.drawable.ic_menu_mark);
}
return rowView;
}
}
public class MainActivity extends ListActivity {
public void onCreate(Bundle SavedInstanceState) {
super.onCreate(SavedInstanceState);
String[] values = new String[] { "Report a Road Delay",
"View Reported Delays", "Search a Road for Delays",
"Update a Delay Report", "Validate a Delay Report" };
MySimpleArrayAdapter adapter = new MySimpleArrayAdapter(this, values);
setListAdapter(adapter);
}
}
This is how it looks so far:
All I basically don't understand is the onClick method; what parameters it takes it, and how to determine which item was clicked. Any help would be appreciated.
Try this:
ListView list1 = getListView();
list1.setOnItemClickListener(
new OnItemClickListener()
{
#Override
public void onItemClick(AdapterView<?> arg0, View view,
int position, long id) {
//Take action here.
}
}
);
You are looking for an OnItemClickListener and not an OnClickListener
lv.setOnItemClickListener(new OnItemClickListener(){
#Override
public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
// DO SOMETHING WITH CICK EVENT HERE
}
}
Now only to discus the params:
parent The AdapterView where the click happened.
view The view within the AdapterView that was clicked
position The position of the view in the adapter.
id The row id of the item that was clicked.
I got the last part from android reference
You could use this code:
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> parentAdapter, View view, int position,
long id) {
// We know the View is a <extView so we can cast it
TextView clickedView = (TextView) view;
Toast.makeText(MainActivity.this, "Item with id ["+id+"] - Position ["+position+"] - Planet ["+clickedView.getText()+"]", Toast.LENGTH_SHORT).show();
}
});
// we register for the contextmneu
registerForContextMenu(lv);
}
where lv is the listView.
If you want to add a context menu:
// We want to create a context Menu when the user long click on an item
#Override
public void onCreateContextMenu(ContextMenu menu, View v,
ContextMenuInfo menuInfo) {
super.onCreateContextMenu(menu, v, menuInfo);
AdapterContextMenuInfo aInfo = (AdapterContextMenuInfo) menuInfo;
// We know that each row in the adapter is a Map
Planet planet = aAdpt.getItem(aInfo.position);
menu.setHeaderTitle("Options for " + planet.getName());
menu.add(1, 1, 1, "Details");
menu.add(1, 2, 2, "Delete");
}
// This method is called when user selects an Item in the Context menu
#Override
public boolean onContextItemSelected(MenuItem item) {
int itemId = item.getItemId();
AdapterContextMenuInfo aInfo = (AdapterContextMenuInfo) item.getMenuInfo();
planetsList.remove(aInfo.position);
aAdpt.notifyDataSetChanged();
return true;
}
If you want to have more information give a look on my blog here and here