0

在以下代码中,findViewById 返回 null:

public void onCreateContextMenu(ContextMenu menu, View view, ContextMenuInfo menuInfo) {
    if (view == this.getListView()) {
        AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo)menuInfo;
        final Message clickedMessage = this.adapter.getItem(info.position);
        menu.setHeaderTitle(clickedMessage.getTitle());
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.showuser_context, menu);
        View button = this.findViewById(R.id.showuser_contextmenu_showthread);
        // I would like to call button.setOnClickListener here
}

和 res/menu/showuser_context.xml:

<?xml version="1.0" encoding="utf-8"?>
<menu
  xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:id="@+id/showuser_contextmenu_showthread" android:title="@string/showuser_contextmenu_showthread"></item>
    <item android:id="@+id/showuser_contextmenu_reply" android:title="@string/showuser_contextmenu_reply"></item>
</menu>

我试图“清理”(项目 - >从eclipse主菜单清理)项目,但它仍然无法正常工作。

问候, ProgVal

4

2 回答 2

1

尝试 :

View button = menu.findViewById(R.id.showuser_contextmenu_showthread);

代替 :

View button = this.findViewById(R.id.showuser_contextmenu_showthread);
于 2011-11-27T15:17:29.173 回答
1

您无法通过 findViewById(); 获取菜单项;相反,你应该使用

@Override
public boolean onContextItemSelected(MenuItem item) {
   if (item.getItemId() == android.R.id.showuser_contextmenu_showthread)
      //Your stuff
      return true;
   }
   return super.onContextItemSelected(item);
}
于 2011-11-27T15:18:05.610 回答