<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content" >
<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="My Movies"
android:textAppearance="?android:attr/textAppearanceLarge"
android:layout_weight="1"
android:gravity="center" />
<ImageButton
android:id="@+id/btn_settings"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/ic_menu_settings_holo_light" />
</LinearLayout>
这是与点击事件的连接:
private ImageButton btn_settings;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btn_settings = (ImageButton)findViewById(R.id.btn_settings);
registerForContextMenu(btn_settings);
这是上下文菜单本身:
@Override
public boolean onContextItemSelected(MenuItem item) {
// TODO Auto-generated method stub
switch (item.getItemId()){
case R.id.Item1:
handler.deleteAllMovies();
break;
case R.id.Item2:
finish();
}
return super.onContextItemSelected(item);
}
@Override
public void onCreateContextMenu(ContextMenu menu, View v,
ContextMenuInfo menuInfo) {
// TODO Auto-generated method stub
super.onCreateContextMenu(menu, v, menuInfo);
MenuInflater inflate = getMenuInflater();
inflate.inflate(R.menu.context, menu);
}
覆盖在oncreate部分之外,btn_settings imagebutton是全局的。 上下文菜单根本没有打开,我做错了什么?
答案 0 :(得分:0)
请修改以下代码,然后重试:
@Override
public void onCreateContextMenu(ContextMenu menu, View v,
ContextMenuInfo menuInfo) {
// TODO Auto-generated method stub
MenuInflater inflate = getMenuInflater();
inflate.inflate(R.menu.context, menu);
super.onCreateContextMenu(menu, v, menuInfo);
}
我希望它能起作用:)。
答案 1 :(得分:0)
对于ContextMenu
,请确保您在图片按钮上长按。否则,只需轻按按钮就不会显示上下文菜单。
来自ContextMenu的文档:
要在长按上显示上下文菜单,大多数客户都希望调用 registerForContextMenu(View)和覆盖 onCreateContextMenu(ContextMenu,View,ContextMenu.ContextMenuInfo)。
如果您希望单击显示上下文菜单,可以手动显示它:
btn_settings = (ImageButton) findViewById(R.id.btn_settings);
registerForContextMenu(btn_settings);
btn_settings.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
view.showContextMenu();
}
});