2 mickey9294 mickey9294 于 2014.08.08 15:43 提问

Android中onContextItemSelected不响应是怎么回事?

在实现一个Contextual Menu时,onCreateContextMenu()是成功执行了的,但长按显示出上下文菜单时,点击其中一个item,onContextItemSelected()中的内容并没有被执行,请问这是为什么?

public class MainActivity extends ActionBarActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    TextView tv = (TextView)findViewById(R.id.hint);
    tv.setText("this is a textview");
    registerForContextMenu(tv);

}

public boolean onContexItemSelected(MenuItem item){
      super.onContextItemSelected(item);
      Log.d("ContextMenu", item.getTitle()+" is selected!");
      Toast.makeText(this, "Hleele;", Toast.LENGTH_LONG).show();
      return false;

  }


  public void onCreateContextMenu(ContextMenu menu, View v,
            ContextMenuInfo menuInfo) {
      super.onCreateContextMenu(menu, v, menuInfo);
        MenuItem cmitem1 = menu.add(0, Menu.FIRST, Menu.NONE, "item1");
        MenuItem cmitem2 = menu.add(0, Menu.FIRST+1, Menu.NONE, "item2");
        MenuItem cmitem3 = menu.add(0, Menu.FIRST+2, Menu.NONE, "item3");
        /*cmitem1.setCheckable(true)
        .setChecked(true);
        cmitem2.setCheckable(true);
        cmitem3.setCheckable(true);*/

    }

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.main, menu);
    return true;
}


@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    int id = item.getItemId();
    if (id == R.id.action_settings) {
        return true;
    }
    return super.onOptionsItemSelected(item);
}

}

1个回答

panhongjin
panhongjin   2014.08.08 16:34

你的onContexItemSelected、onCreateContextMenu需要继承activity的,onContexItemSelected方法中的super要去掉,返回true就ok了。我的代码是:

@Override
public void onCreateContextMenu(ContextMenu menu, View v,
        ContextMenuInfo menuInfo) {
    super.onCreateContextMenu(menu, v, menuInfo);
    menu.add(0, Menu.FIRST, Menu.NONE, "item1");
    menu.add(0, Menu.FIRST + 1, Menu.NONE, "item2");
    menu.add(0, Menu.FIRST + 2, Menu.NONE, "item3");

}

@Override
public boolean onContextItemSelected(MenuItem item) {
    Log.d("ContextMenu", item.getTitle() + " is selected!");
    Toast.makeText(this, "Hleele;", Toast.LENGTH_LONG).show();
    return true;
}
mickey9294
mickey9294 啊,可以了,刚刚拼错了单词……谢谢!
3 年多之前 回复
mickey9294
mickey9294 试了一下把super去掉结果还是不行呀。“那两个方法要继承activity的”这句没看懂,这两个方法本来就是重写的activity里的方法呀。还请前辈指教!
3 年多之前 回复
Csdn user default icon
上传中...
上传图片
插入图片
准确详细的回答,更有利于被提问者采纳,从而获得C币。复制、灌水、广告等回答会被删除,是时候展现真正的技术了!