我想在点击按钮时打开上下文菜单,但是我也需要知道当我点击按钮时哪个列表项获得了焦点。你知道如何做到这一点吗?onclick
方法中应该放什么代码?
我想在点击按钮时打开上下文菜单,但是我也需要知道当我点击按钮时哪个列表项获得了焦点。你知道如何做到这一点吗?onclick
方法中应该放什么代码?
我也在寻找同样的内容,后来发现应该使用对话框(Dialogs)而不是上下文菜单(context menu)
final CharSequence[] items = {"Red", "Green", "Blue"};
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Pick a color");
builder.setItems(items, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int item) {
Toast.makeText(getApplicationContext(), items[item], Toast.LENGTH_SHORT).show();
}
});
AlertDialog alert = builder.create();
alert.show();
http://developer.android.com/guide/topics/ui/dialogs.html#AlertDialog
registerForContextMenu
。然后在实际的按钮 onClick 处理程序中,调用 openContextMenu(View)
。<Button
android:id="@+id/btn_help"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="onHelp"
android:text="@string/help_btn_text" />
在我的 onCreate 方法中
registerForContextMenu(findViewById(R.id.btn_help));
并且在 onHelp 函数中
public void onHelp(View v) {
openContextMenu(v);
}
这能够正常工作是因为视图v与注册了上下文菜单的视图是相同的。
首先,您应该通过调用registerForContextMenu(View view)来注册视图。其次,覆盖onCreateContextMenu()以添加菜单,最后,覆盖onContextItemSelected()以在每个菜单上放置逻辑。
ContextMenu
。一个视图的ContextMenu
功能类似于PC上的右键菜单,这意味着对某个项目的“可用操作”。ListView
中的焦点项。然后,你可以保存ContextMenu
的注册信息,以供真正需要菜单的视图使用 :)