How to show contextmenu on inflated view?
I want to display contextmenu for an inflated view. Here is the code sample:
for grid_layout.xml:
<?xml version="1.0" encoding="utf-8"?>
<ImageView
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/icon"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:scaleType="centerInside"
android:antialias="true" />
Now I am using it in my activiy class as:
@Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {
menu.setHeaderTitle("Select action");
menu.add(0, 1, 0, "Action1");
menu.add(0, 2, 0, "Action2");
super.onCreateContextMenu(menu, v, menuInfo);
}
LayoutInflater inflater = (LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
ImageView imageView = (ImageView) inflater.inflate(R.layout.grid_layout, null);
imageView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
registerForContextMenu(v);
openContextMenu(v);
}
});
This code runs without any error but the context menu does not show up when I click the imageView. Is there anything wrong with this code?开发者_运维百科
I have found a workaround for this situation and solved my problem. As I told that the same code works fine and displays the ContextMenu, if I define the ImageView in the XML which I set in setContentView() method. I simply used the object of that imageView to register the contextMenu and displayed the ContextMenu on click of inflated item. Here is the sample code:
@Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {
menu.setHeaderTitle("Select action");
menu.add(0, 1, 0, "Action1");
menu.add(0, 2, 0, "Action2");
super.onCreateContextMenu(menu, v, menuInfo);
}
ImageView imageViewInContext = (ImageView) findViewById(R.id.imageview_in_main_xml);
registerForContextMenu(imageViewInContext);
LayoutInflater inflater = (LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
ImageView imageView = (ImageView) inflater.inflate(R.layout.grid_layout, null);
imageView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
openContextMenu(imageViewInContext);
}
});
Hope this will help someone!
Add in your code:
imageView.setFocusable(true);
imageView.setClickable(true);
after that Imageview will get clickEvent.
Because you are creating an Anonymous Inner Class (by doing new View.OnClickListener
) you are no longer operating in the UI thread (your Activity class), so the context menu does not load when you want to registerForContextMenu
and openContextMenu
. You can either use a Handler
to send a message to the UI thread(your Activity class) to perform these actions, or try to reference your Activity class in your inner class. Something like this:
activityClassName.this.registerForContextMenu(v);
activityClassName.this.openContextMenu(v);
精彩评论