I'm newbie in Android and i learning context menu but after surfing about context menu i have little bit confusion in Adapter and Inflater. I saw 1 program with using adapter and 1 using Inflater. So, please help me how/when to use Adapter and Inflater.
Here is an example using inflater...
public class MainActivity extends ListActivity {
private String selectedName = "";
private String[] nameList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
nameList = getResources().getStringArray(R.array.name_list);
setListAdapter(new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, nameList));
registerForContextMenu(getListView());
}
public void onCreateContextMenu(ContextMenu menu, View v,
ContextMenuInfo menuInfo) {
getMenuInflater().inflate(R.menu.context_menu, menu);
}
public boolean onContextItemSelected(MenuItem item) {
AdapterContextMenuInfo adapInfo = (AdapterContextMenuInfo) item
.getMenuInfo();
selectedName = nameList[(int) adapInfo.id];
switch (item.getItemId()) {
case R.id.view:
Toast.makeText(MainActivity.this,
"You have pressed View Context Menu for " + selectedName,
Toast.LENGTH_LONG).show();
return true;
case R.id.save:
Toast.makeText(MainActivity.this,
"You have pressed Save Context Menu for " + selectedName,
Toast.LENGTH_LONG).show();
return true;
case R.id.edit:
Toast.makeText(MainActivity.this,
"You have pressed Edit Context Menu for " + selectedName,
Toast.LENGTH_LONG).show();
return true;
case R.id.delete:
Toast.makeText(MainActivity.this,
"You have pressed Delete Context Menu for " + selectedName,
Toast.LENGTH_LONG).show();
return true;
}
return false;
}
}
Another example using adapter:
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Countries = getResources().getStringArray(R.array.Game);
ListView list = (ListView) findViewById(R.id.list);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
R.layout.listitem, Countries);
list.setAdapter(adapter);
registerForContextMenu(list);
}
public void onCreateContextMenu(ContextMenu menu, View v,
ContextMenuInfo menuInfo) {
if (v.getId() == R.id.list) {
AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo) menuInfo;
menu.setHeaderTitle(Countries[info.position]);
String[] menuItems = getResources().getStringArray(
R.array.contextmenu);
for (int i = 0; i < menuItems.length; i++) {
menu.add(Menu.NONE, i, i, menuItems[i]);
}
}
}
public boolean onContextItemSelected(MenuItem item) {
// TODO Auto-generated method stub
AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo) item
.getMenuInfo();
int menuItemIndex = item.getItemId();
String[] menuItems = getResources().getStringArray(R.array.contextmenu);
String[] menuItems1 = getResources().getStringArray(R.array.game);
String menuItemName = menuItems[menuItemIndex];
String listItemName = menuItems1[info.position];
// selectedName = nameList[(int) info.id];
TextView text = (TextView) findViewById(R.id.textView1);
text.setText(String.format("Selected %s for item %s", menuItemName,
listItemName));
return true;
}
These types serve different purposes.
The MenuInflator converts XML files into a Menu object representing the on-screen layout of the menu. In the first example, R.menu.context_menu refers to an associated XML file at res/menu/context_menu.xml that defines the choices that will appear in the menu. See Menu Resource for the format of XML menu resources. Here's a simple example:
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">
<item android:id="#+id/open" android:title="Open"/>
<item android:id="#+id/info" android:title="More Info"/>
<item android:id="#+id/delete" android:title="Delete"/>
</menu>
The AdapterContextMenuInfo provides extra information when a context menu is brought up for a list, grid, etc. It allows you to determine which item the user selected (long pressed). Notice that both of your examples use this.
Related
In my application I'm register ContextMenu on Listview and I want to get clicked Listview item by context menu. For example if I have two row in list view with this structure:
public class StructReceiveSms{
public int userID;
public String username;
}
my adapter can be show username in listview. now i'm in below code can define conext menu on list view:
public class FragmentSmsReceiveMaster extends Fragment {
private static final Boolean DEBUG = true;
public ArrayAdapter adapter;
private ArrayList<StructReceiveSms> receiveSmsArray;
.
.
.
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
.
.
.
smsView = (ListView) view.findViewById(R.id.listView);
smsView.setAdapter(adapter);
registerForContextMenu(smsView);
.
.
.
}
#Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {
AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo) menuInfo;
String[] menuItems = getResources().getStringArray(R.array.SmsMasterContextMenu);
for (int i = 0; i < menuItems.length; i++) {
menu.add(Menu.NONE, i, i, menuItems[i]);
}
}
#Override
public boolean onContextItemSelected(MenuItem item) {
AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo) item.getMenuInfo();
int menuItemIndex = item.getItemId();
String listItemName = adapter.getItem(info.position) + "";
/* GET CLICKED LISTVIEW ITEM AFTER CHOOSE CONTEXTMENU MENU ITEMS */
Toast.makeText(G.currentActivity, listItemName, Toast.LENGTH_SHORT).show();
return true;
}
}
Now after click on context menu items I can get which clicked by user by menuItemIndex but I can not get which Listview's items in onContextItemSelected function. for example ater opening context menu on first item I can get userID and username and show it. How to do this, thanks
Since your Adapter's data list consists of StructReceiveSms objects, the adapter.getItem(info.position) call in onContextItemSelected() will return the list item the context menu was opened for, but it will need to be cast to the StructReceiveSms type. From this, you can get the userID and username you want.
public boolean onContextItemSelected(MenuItem item)
{
...
StructReceiveSms listItem = (StructReceiveSms) adapter.getItem(info.position);
String selectedName = listItem.username;
int selectedId = listItem.userID;
...
}
This is assuming you've not overridden the getItem() method of the Adapter to return something else, but I imagine you would've shown that if you had.
I am developing an android application.I will have a listview and i have set a context menu to appear when a listview item is long-pressed.How do i get the item from the listview item selected(say text from a listview textview) after an action from the contextmenu is chosen so i can process it?
Here is some code:
protected void onCreate(Bundle savedInstanceState) {
-------
lv1 = (ListView) findViewById(R.id.listings);
registerForContextMenu(lv1);
lv1.setOnItemClickListener(this);
}
And the onCreateContextMenu:
public void onCreateContextMenu(ContextMenu menu, View v,
ContextMenuInfo menuInfo) {
super.onCreateContextMenu(menu, v, menuInfo);
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.context_menu, menu);
}
#Override
public boolean onContextItemSelected(MenuItem item) {
AdapterContextMenuInfo info = (AdapterContextMenuInfo) item
.getMenuInfo();
switch (item.getItemId()) {
case R.id.watch:
String name = "";
return true;
case R.id.buy:
return true;
default:
return super.onContextItemSelected(item);
}
}
I want to get text from a textview in a list item.How do i achieve that?
To get the item from the ListView item selected refer to ContextMenuInfo object (see last implemented method below). Full solution as follows:
1) register ListView for context menu in ListActivity class
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// ...
getListView().setAdapter(mAdapter);
registerForContextMenu(getListView());
}
1a) if you have complex View on your list you might need to enable long click on each list view in Adapter class
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View view = convertView;
if (view == null) {
RelativeLayout layout = (RelativeLayout) LayoutInflater.from(mContext).inflate(R.layout.list_item, parent, false);
itemLayout = layout;
itemLayout.setLongClickable(true);
}
// ...
return view;
}
2) implement onCreateContextMenu() and onContextItemSelected() in ListActivity class
#Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {
super.onCreateContextMenu(menu, v, menuInfo);
AdapterContextMenuInfo info = (AdapterContextMenuInfo) menuInfo;
String title = ((MyItem) mAdapter.getItem(info.position)).getTitle();
menu.setHeaderTitle(title);
menu.add(Menu.NONE, MENU_CONTEXT_DELETE_ID, Menu.NONE, DELETE_TEXT);
}
#Override
public boolean onContextItemSelected(MenuItem item) {
switch (item.getItemId()) {
case MENU_CONTEXT_DELETE_ID:
AdapterContextMenuInfo info = (AdapterContextMenuInfo) item.getMenuInfo();
Log.d(TAG, "removing item pos=" + info.position);
mAdapter.remove(info.position);
return true;
default:
return super.onContextItemSelected(item);
}
}
The problem was the onItemLongClick() method, do not use it for context menu.
Instead, register the LISTVIEW for the context menu.
Here's the source.
for 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);
}
}
1) First we use
#Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {
super.onCreateContextMenu(menu, v, menuInfo);
menu.add("View Selected Text");
}
2)
list--is ref if ListView
registerForContextMenu(list);
3)
#Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {
super.onCreateContextMenu(menu, v, menuInfo);
if(item.getTitle().equals("View Selected Text"))
{
AdapterContextMenuInfo menuInfo = (AdapterContextMenuInfo) item.getMenuInfo();
Contact c=array.get(menuInfo.position);
Toast.makeText(List.this, "Selected String is :-"+c.toString(), Toast.LENGTH_SHORT).show();
}
}
first get list using id
Context context = getApplicationContext();
ComponentName component = new ComponentName(context.getPackageName(), TestReplaceHomeAppActivity.class.getName());
String packname = context.getPackageName();
Intent LaunchIntent = getActivity().getPackageManager().getLaunchIntentForPackage(packageName);
if(LaunchIntent != null){
startActivity(LaunchIntent);
}
else {
Toast.makeText(getActivity().getBaseContext(),"APPLICATION IN NOT AVAILABEL", Toast.LENGTH_SHORT).show();
}
Write this in your longPressListener with the listview you use:
ListView list = (ListView) findViewById(android.R.id.list);
registerForContextMenu(list);
And this are the methods:
#Override
public void onCreateContextMenu(ContextMenu menu, View v,
ContextMenuInfo menuInfo) {
super.onCreateContextMenu(menu, v, menuInfo);
AdapterContextMenuInfo info = (AdapterContextMenuInfo) menuInfo;
Adapter adapter = getListAdapter();
Object item = adapter.getItem(info.position);
menu.setHeaderTitle("Choose");
menu.add(0, v.getId(), 0, "Delete");
}
#Override
public boolean onContextItemSelected(MenuItem item) {
if (item.getTitle() == "Delete") {
deleteContact(item.getItemId());
} else if (...) {
// code
} else {
return false;
}
return true;
}
public void deleteContact(int id){
// your code what to do for the clicked item
}
use these methods, onCreateContextMenu and onContextItemSelected\
#Override
public void onCreateContextMenu(ContextMenu menu, View v,
ContextMenuInfo menuInfo) {
if (v.getId() == R.id.listview) {
menu.setHeaderTitle("Delete");
menu.add(Menu.NONE, 0, 0, "Delete from list");
}
}
/**
* Responding to context menu selected option
* */
#Override
public boolean onContextItemSelected(MenuItem item) {
AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo) item
.getMenuInfo();
int menuItemIndex = item.getItemId();
// check for selected option
if (menuItemIndex == 0) {
// user selected delete
// delete the listrow
..(in your onitemclicklistener there is a parameter called as'postition' use this position and use some method to delete the data corresponding to the position value )
// reloading same activity again
Intent intent = getIntent();
finish();
startActivity(intent);
}
return true;
}
The above answers are very accurate and to the point for the case provided. That being said, I was brought here with using a convertView for my listview and am answering for those who are also brought here with this case.
If your LISTVIEW is using convertView and inflating a separate layout (say list_MyItem.xml), directly modify the list_MyItem.xml to have:
android:longClickable="true"
For example, if the listview is being populated with buttons modify the button as such:
<Button
android:id="#+id/myButton"
.
.
.
android:longClickable="true"
/>
I am developing an android application.I will have a listview and i have set a context menu to appear when a listview item is long-pressed.How do i get the item from the listview item selected(say text from a listview textview) after an action from the contextmenu is chosen so i can process it?
Here is some code:
protected void onCreate(Bundle savedInstanceState) {
-------
lv1 = (ListView) findViewById(R.id.listings);
registerForContextMenu(lv1);
lv1.setOnItemClickListener(this);
}
And the onCreateContextMenu:
public void onCreateContextMenu(ContextMenu menu, View v,
ContextMenuInfo menuInfo) {
super.onCreateContextMenu(menu, v, menuInfo);
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.context_menu, menu);
}
#Override
public boolean onContextItemSelected(MenuItem item) {
AdapterContextMenuInfo info = (AdapterContextMenuInfo) item
.getMenuInfo();
switch (item.getItemId()) {
case R.id.watch:
String name = "";
return true;
case R.id.buy:
return true;
default:
return super.onContextItemSelected(item);
}
}
I want to get text from a textview in a list item.How do i achieve that?
To get the item from the ListView item selected refer to ContextMenuInfo object (see last implemented method below). Full solution as follows:
1) register ListView for context menu in ListActivity class
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// ...
getListView().setAdapter(mAdapter);
registerForContextMenu(getListView());
}
1a) if you have complex View on your list you might need to enable long click on each list view in Adapter class
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View view = convertView;
if (view == null) {
RelativeLayout layout = (RelativeLayout) LayoutInflater.from(mContext).inflate(R.layout.list_item, parent, false);
itemLayout = layout;
itemLayout.setLongClickable(true);
}
// ...
return view;
}
2) implement onCreateContextMenu() and onContextItemSelected() in ListActivity class
#Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {
super.onCreateContextMenu(menu, v, menuInfo);
AdapterContextMenuInfo info = (AdapterContextMenuInfo) menuInfo;
String title = ((MyItem) mAdapter.getItem(info.position)).getTitle();
menu.setHeaderTitle(title);
menu.add(Menu.NONE, MENU_CONTEXT_DELETE_ID, Menu.NONE, DELETE_TEXT);
}
#Override
public boolean onContextItemSelected(MenuItem item) {
switch (item.getItemId()) {
case MENU_CONTEXT_DELETE_ID:
AdapterContextMenuInfo info = (AdapterContextMenuInfo) item.getMenuInfo();
Log.d(TAG, "removing item pos=" + info.position);
mAdapter.remove(info.position);
return true;
default:
return super.onContextItemSelected(item);
}
}
The problem was the onItemLongClick() method, do not use it for context menu.
Instead, register the LISTVIEW for the context menu.
Here's the source.
for 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);
}
}
1) First we use
#Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {
super.onCreateContextMenu(menu, v, menuInfo);
menu.add("View Selected Text");
}
2)
list--is ref if ListView
registerForContextMenu(list);
3)
#Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {
super.onCreateContextMenu(menu, v, menuInfo);
if(item.getTitle().equals("View Selected Text"))
{
AdapterContextMenuInfo menuInfo = (AdapterContextMenuInfo) item.getMenuInfo();
Contact c=array.get(menuInfo.position);
Toast.makeText(List.this, "Selected String is :-"+c.toString(), Toast.LENGTH_SHORT).show();
}
}
first get list using id
Context context = getApplicationContext();
ComponentName component = new ComponentName(context.getPackageName(), TestReplaceHomeAppActivity.class.getName());
String packname = context.getPackageName();
Intent LaunchIntent = getActivity().getPackageManager().getLaunchIntentForPackage(packageName);
if(LaunchIntent != null){
startActivity(LaunchIntent);
}
else {
Toast.makeText(getActivity().getBaseContext(),"APPLICATION IN NOT AVAILABEL", Toast.LENGTH_SHORT).show();
}
Write this in your longPressListener with the listview you use:
ListView list = (ListView) findViewById(android.R.id.list);
registerForContextMenu(list);
And this are the methods:
#Override
public void onCreateContextMenu(ContextMenu menu, View v,
ContextMenuInfo menuInfo) {
super.onCreateContextMenu(menu, v, menuInfo);
AdapterContextMenuInfo info = (AdapterContextMenuInfo) menuInfo;
Adapter adapter = getListAdapter();
Object item = adapter.getItem(info.position);
menu.setHeaderTitle("Choose");
menu.add(0, v.getId(), 0, "Delete");
}
#Override
public boolean onContextItemSelected(MenuItem item) {
if (item.getTitle() == "Delete") {
deleteContact(item.getItemId());
} else if (...) {
// code
} else {
return false;
}
return true;
}
public void deleteContact(int id){
// your code what to do for the clicked item
}
use these methods, onCreateContextMenu and onContextItemSelected\
#Override
public void onCreateContextMenu(ContextMenu menu, View v,
ContextMenuInfo menuInfo) {
if (v.getId() == R.id.listview) {
menu.setHeaderTitle("Delete");
menu.add(Menu.NONE, 0, 0, "Delete from list");
}
}
/**
* Responding to context menu selected option
* */
#Override
public boolean onContextItemSelected(MenuItem item) {
AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo) item
.getMenuInfo();
int menuItemIndex = item.getItemId();
// check for selected option
if (menuItemIndex == 0) {
// user selected delete
// delete the listrow
..(in your onitemclicklistener there is a parameter called as'postition' use this position and use some method to delete the data corresponding to the position value )
// reloading same activity again
Intent intent = getIntent();
finish();
startActivity(intent);
}
return true;
}
The above answers are very accurate and to the point for the case provided. That being said, I was brought here with using a convertView for my listview and am answering for those who are also brought here with this case.
If your LISTVIEW is using convertView and inflating a separate layout (say list_MyItem.xml), directly modify the list_MyItem.xml to have:
android:longClickable="true"
For example, if the listview is being populated with buttons modify the button as such:
<Button
android:id="#+id/myButton"
.
.
.
android:longClickable="true"
/>
Hello stackoverflow community,
Basically, i have gallery displaying some images using a gridView + imageView
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent" android:layout_height="fill_parent">
<GridView android:id="#+id/PhoneImageGrid"
android:layout_width="fill_parent" android:layout_height="fill_parent"
android:numColumns="auto_fit" android:verticalSpacing="12dp"
android:horizontalSpacing="12dp" android:columnWidth="90dp"
android:stretchMode="columnWidth" android:gravity="center" />
<ImageView android:id="#+id/thumbImage" android:layout_width="wrap_content"
android:layout_height="wrap_content" android:layout_centerInParent="true"
android:scaleType="centerCrop"
/>
I would like to use setOnLongClick for each imageView displayed by the adapter.
This works well, however, when clicking long on the imageView, i would like to display a ContextMenu with some items ( i.e, you long click on an imageView, a contextMenu is displayed with some items : Image information, send this image ...).
Unfortunatly, i can't figure out how to inflate this menu in the adapter.(Probably not the good way to do it )
I have the following lines in my main activity
_adapter = new ImageAdapter(activity,storedObjects.getAlbums());
imagegrid.setAdapter(_adapter);
My adapter ( some useless lines removed )
public class ImageAdapter extends BaseAdapter {
private Albums albums;
private Context context;
private LayoutInflater inflater;
public ImageAdapter(Context context, Albums albums) {
this.albums = albums;
this.context = context;
inflater = (LayoutInflater)context.getSystemService (Context.LAYOUT_INFLATER_SERVICE);
if(albums.getAlbumsListSize() == 0) {
Toast.makeText(context, "There is no album to display", Toast.LENGTH_LONG).show();
}
}
public View getView(final int position, View view, ViewGroup parent) {
ViewHolder holder;
if (view == null) {
holder = new ViewHolder();
view = inflater.inflate(R.layout.galleryitem, null);
holder.imageview = (ImageView) view.findViewById(R.id.thumbImage);
holder.checkbox = (CheckBox) view.findViewById(R.id.itemCheckBox);
holder.textview = (TextView) view.findViewById(R.id.album_name);
holder.checkbox.setChecked(true);
//Bitmap loadingBM = BitmapFactory.decodeResource(context.getResources(),R.drawable.loading_image);
//holder.imageview.setImageBitmap(loadingBM);
view.setTag(holder);
}
else {
holder = (ViewHolder) view.getTag();
}
holder.imageview.setClickable(true);
holder.imageview.setOnLongClickListener(new OnLongClickListener() {
public boolean onLongClick(View v) {
Log.v(TAG,"onLongClick ok !");
return false;
}
});
imageDownloader.download(this.context, albums.getAllAlbums().get(position).getThumbnailUri(), holder.imageview);
return view;
}
Questions :
setOnLongClickListener works properly, when i click on an image, my Log is displayed in logcat, however, how to create a menu for each imageView ?
Apparently, i can only override onCreateContextMenu in my main activity. I guess i could pass each ImageView to onCreateContextMenu(ContextMenu menu, View v,ContextMenuInfo menuInfo) but how ?
I would be really grateful if you could help me out with this.
Thank you very much
Florent Valdelievre
Instead of setOnLongClickListener on the ImageView, call registerForContextMenu with your GridView. Then, implement onCreateContextMenu and onContextItemSelected.
Here is a simple ListActivity to show you how it works.
public class GreetingActivity extends ListActivity {
private static final String[] mGreetings = { "Hello", "Goodbye" };
private static final String[] mPeople = { "Alice", "Bob", "Charlie" };
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, mPeople);
setListAdapter(adapter);
ListView listView = getListView();
registerForContextMenu(listView);
}
#Override
public void onCreateContextMenu(ContextMenu menu, View v,
ContextMenu.ContextMenuInfo menuInfo) {
for (int i = 0; i < mGreetings.length; ++i) {
String greeting = mGreetings[i];
menu.add(v.getId(), i, ContextMenu.NONE, "Say " + greeting);
}
}
#Override
public boolean onContextItemSelected(MenuItem item) {
AdapterView.AdapterContextMenuInfo menuInfo
= (AdapterView.AdapterContextMenuInfo) item.getMenuInfo();
int adapterPosition = menuInfo.position;
String person = mPeople[adapterPosition];
int menuItemId = item.getItemId();
String greeting = mGreetings[menuItemId];
String msg = String.format("%s, %s!", greeting, person);
Toast.makeText(this, msg, Toast.LENGTH_SHORT).show();
return true;
}
}
Thank you so much #chiuki, it works as expected
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
...
final GridView imagegrid = (GridView) findViewById(R.id.PhoneImageGrid);
registerForContextMenu(imagegrid);
storedObjects.storeThumbnailsURI();
_adapter = new ImageAdapter(activity,storedObjects.getAlbums());
imagegrid.setAdapter(_adapter);
}
#Override
public void onCreateContextMenu(ContextMenu menu, View v,ContextMenuInfo menuInfo) {
AdapterContextMenuInfo info = (AdapterContextMenuInfo) menuInfo;
Log.v("context menu","context menu");
menu.setHeaderTitle("Context Menu");
menu.add(0, START_SLIDESHOW_ON_THIS_ALBUM, 0, "Start SlideShow for this Album");
menu.add(0, DOWNLOAD_WHOLE_ALBUM, 0, "Download this Album");
}
#Override
public boolean onContextItemSelected(MenuItem item) {
AdapterContextMenuInfo info = (AdapterContextMenuInfo) item.getMenuInfo();
switch (item.getItemId()) {
case START_SLIDESHOW_ON_THIS_ALBUM:
selectThisAlbumOnly(info);
startSlideShow();
break;
case DOWNLOAD_WHOLE_ALBUM:
break;
}
return true;
}
In the Adapter, make sure you don't have any setClickable = true
Cheers
Florent
I have a ListView that will allow the user to long-press an item to get a context menu. The problem I'm having is in determining which ListItem they long-pressed. I've tried doing this:
myListView.setOnCreateContextMenuListener(new OnCreateContextMenuListener() {
#Override public void onCreateContextMenu(ContextMenu menu, final View v, ContextMenuInfo menuInfo) {
menu.add("Make Toast")
.setOnMenuItemClickListener(new OnMenuItemClickListener() {
#Override public boolean onMenuItemClick(MenuItem item) {
String toastText = "You clicked position " + ((ListView)v).getSelectedItemPosition();
Toast.makeText(DisplayScheduleActivity.this, toastText, Toast.LENGTH_SHORT).show();
return true;
}
});
}
});
but it just hangs until an ANR pops up. I suspect that after the menu is created the ListItem is no longer selected.
It looks like you could monitor for clicks or long-clicks then record the clicked item there:
mArrivalsList.setOnItemLongClickListener(new OnItemLongClickListener() {
#Override public boolean onItemLongClick(AdapterView<?> parent, View v, int position, long id) {
// record position/id/whatever here
return false;
}
});
but that feels majorly kludgey to me. Does anyone have any better solutions for this?
I do exactly this. In my onCreateContextMenu(...) method, I cast the ContextMenu.ContextMenuInfo to AdapterView.AdapterContextMenuInfo. From there, you can get the targetView, which you cast again to the widget. The complete code is available in HomeActivity.java, look for the onCreateContextMenu(...) method.
#Override
public void onCreateContextMenu(ContextMenu contextMenu,
View v,
ContextMenu.ContextMenuInfo menuInfo) {
AdapterView.AdapterContextMenuInfo info =
(AdapterView.AdapterContextMenuInfo) menuInfo;
selectedWord = ((TextView) info.targetView).getText().toString();
selectedWordId = info.id;
contextMenu.setHeaderTitle(selectedWord);
contextMenu.add(0, CONTEXT_MENU_EDIT_ITEM, 0, R.string.edit);
contextMenu.add(0, CONTEXT_MENU_DELETE_ITEM, 1, R.string.delete);
}
Note that I store the selected text as well as the select id in private fields. Since the UI is thread confined, I know the selectedWord and selectedWordId fields will be correct for later actions.
First of all, I'm wondering if you're making things a little overly complicated by using View.setOnCreateContextMenuListener(). Things get a lot easier if you use Activity.registerForContextMenu(), because then you can just use Activity.onCreateContextMenu() and Activity.onContextItemSelected() to handle all of your menu events. It basically means you don't have to define all these anonymous inner classes to handle every event; you just need to override a few Activity methods to handle these context menu events.
Second, there's definitely easier ways to retrieve the currently selected item. All you need to do is keep a reference either to the ListView or to the Adapter used to populate it. You can use the ContextMenuInfo as an AdapterContextMenuInfo to get the position of the item; and then you can either use ListView.getItemAtPosition() or Adapter.getItem() to retrieve the Object specifically linked to what was clicked. For example, supposing I'm using Activity.onCreateContextMenu(), I could do this:
#Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {
super.onCreateContextMenu(menu, v, menuInfo);
// Get the info on which item was selected
AdapterContextMenuInfo info = (AdapterContextMenuInfo) menuInfo;
// Get the Adapter behind your ListView (this assumes you're using
// a ListActivity; if you're not, you'll have to store the Adapter yourself
// in some way that can be accessed here.)
Adapter adapter = getListAdapter();
// Retrieve the item that was clicked on
Object item = adapter.getItem(info.position);
}
#Override
public boolean onContextItemSelected(MenuItem item) {
// Here's how you can get the correct item in onContextItemSelected()
AdapterContextMenuInfo info = (AdapterContextMenuInfo) item.getMenuInfo();
Object item = getListAdapter().getItem(info.position);
}
this is another way on how to create context menu n how to delete the item selected here is the whole code
public class SimpleJokeList extends Activity {
public static final int Upload = Menu.FIRST + 1;
public static final int Delete = Menu.FIRST + 2;
int position;
ListView lv;
EditText jokeBox;
Button addJoke;
MyAdapter adapter;
private ArrayAdapter<String> mAdapter;
private ArrayList<String> mStrings = new ArrayList<String>();
String jokesToBeAdded;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.simplejokeui);
lv=(ListView)findViewById(R.id.jokelist);
addJoke=(Button)findViewById(R.id.addjoke);
jokeBox=(EditText)findViewById(R.id.jokebox);
mAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, mStrings);
registerForContextMenu(lv);
listItemClicked();
addJokes();
private void addJokes() {
// TODO Auto-generated method stub
addJoke.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
jokesToBeAdded=jokeBox.getText().toString();
if(jokesToBeAdded.equals("")){
Toast.makeText(getApplicationContext(), "please enter some joke", Toast.LENGTH_LONG).show();
}
else{
lv.setAdapter(mAdapter);
mAdapter.add(jokesToBeAdded);
jokeBox.setText(null);
}
}
});
}
private void listItemClicked() {
// TODO Auto-generated method stub
lv.setOnItemLongClickListener(new OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> arg0, View arg1,
int arg2, long arg3) {
// TODO Auto-generated method stub
position=arg2;
return false;
}
});
}
#Override
public void onCreateContextMenu(ContextMenu menu, View v,
ContextMenuInfo menuInfo) {
// TODO Auto-generated method stub
super.onCreateContextMenu(menu, v, menuInfo);
populateMenu(menu);
menu.setHeaderTitle("Select what you wanna do");
}
private void populateMenu(ContextMenu menu) {
// TODO Auto-generated method stub
menu.add(Menu.NONE, Upload, Menu.NONE, "UPLOAD");
menu.add(Menu.NONE, Delete, Menu.NONE, "DELETE");
}
#Override
public boolean onContextItemSelected(MenuItem item)
{
return (applyMenuChoice(item) || super.onContextItemSelected(item));
}
private boolean applyMenuChoice(MenuItem item) {
// TODO Auto-generated method stub
switch (item.getItemId())
{
case Delete:
String s=mAdapter.getItem(position);
mAdapter.remove(s);
// position--;
Toast.makeText(getApplicationContext(),"Congrats u HAve Deleted IT", Toast.LENGTH_LONG).show();
return (true);
}
return false;
}
And don't forget to put this
registerForContextMenu(listview);
in your onCreate method to get your context Menu visible.
We have used with success:
#Override
public boolean onContextItemSelected
(
MenuItem item
)
{
if (!AdapterView.AdapterContextMenuInfo.class.isInstance (item.getMenuInfo ()))
return false;
AdapterView.AdapterContextMenuInfo cmi =
(AdapterView.AdapterContextMenuInfo) item.getMenuInfo ();
Object o = getListView ().getItemAtPosition (cmi.position);
return true;
}
Isn't the view argument the actual selected row's view, or am I missing the question here?
ListView lv;
private OnItemLongClickListener onLongClick = new OnItemLongClickListener() {
public boolean onItemLongClick(AdapterView<?> arg0, View arg1,
int arg2, long arg3) {
lv.showContextMenuForChild(arg1);
lv.showContextMenu();
return false;
}
};
#Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {
super.onCreateContextMenu(menu, v, menuInfo);
AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo) menuInfo;
View TargetV=(View) info.targetView;
text1 = (String) ((TextView) TargetV.findViewById(R.id.textView1)).getText();
text2 = (String) ((TextView) TargetV.findViewById(R.id.textView2)).getText();
if(List3Ok){
text3 = (String) ((TextView) TargetV.findViewById(R.id.textView3)).getText();
}
selectedWord = text1 + "\n" + text2 + "\n" + text3;
selectedWordId = info.id;
menu.setHeaderTitle(selectedWord);
MenuInflater inflater = this.getActivity().getMenuInflater();
inflater.inflate(R.menu.list_menu, menu);
}
I case you are using SimpleCursorAdapder you may do it like this
#Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {
getActivity().getMenuInflater().inflate(R.menu.project_list_item_context, menu);
// Getting long-pressed item position
AdapterContextMenuInfo info = (AdapterContextMenuInfo) menuInfo;
int position = info.position;
// Get all records from adapter
Cursor c = ((SimpleCursorAdapter)getListAdapter()).getCursor();
// Go to required position
c.moveToPosition(position);
// Read database fields values associated with our long-pressed item
Log.d(TAG, "Long-pressed-item with position: " + c.getPosition());
Log.d(TAG, "Long-pressed-item _id: " + c.getString(0));
Log.d(TAG, "Long-pressed-item Name: " + c.getString(1));
Log.d(TAG, "Long-pressed-item Date: " + c.getString(2));
Log.d(TAG, "Long-pressed-item Path: " + c.getString(3));
// Do whatever you need here with received values
}