2011-11-27 31 views
0

在下面的代碼,findViewById返回null:findViewById虛增菜單

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 /菜單/ 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> 

我tryed爲 「乾淨」(項目 - >清除從eclipse主菜單)該項目,但它仍然無法正常工作。

問候, ProgVal

回答

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); 
} 
1

嘗試:

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

代替:

View button = this.findViewById(R.id.showuser_contextmenu_showthread); 
+0

好主意,但它仍然返回null。 'view'代替'this'。 –

+0

從邏輯上講,它應該有效,因爲你已經在你的菜單中誇大了你的xml,所以當你嘗試使用它來查找視圖時,它會搜索你的Activity的ContentView上的視圖(而不是菜單),這就是爲什麼你應該在你的菜單實例中找到你的意見 – Houcine