2012-07-10 82 views
1

我有一個活動繼承自ListActivity並使用AndroidAnnotations。雖然.onListItemClick工作正常,但列表項目的上下文菜單根本沒有出現,即使.onCreateContextMenu未被調用,但.onListItemClick在長按一下列表項目後也會觸發。這裏是我的代碼:ListActivity中的AndroidAnnotations和上下文菜單

@OptionsMenu(R.menu.places) 
@EActivity(R.layout.places) 
public class PlacesPicker extends ListActivity { 

    private static String[] DATA_SOURCE = { PlacesDB.PLACE_NAME, PlacesDB.PLACE_DESC }; 
    private static int[] DATA_DESTINATION = { R.id.place_name, R.id.place_desc }; 

    public static ListView lv; 

    @Bean 
    PlacesDB db; 

    Cursor cursor; 

    @AfterInject 
    public void init() { 

     cursor = db.getPlaces(null, null); 
     startManagingCursor(cursor); 

     SimpleCursorAdapter adapter = new SimpleCursorAdapter(this, R.layout.place_item, cursor, DATA_SOURCE, DATA_DESTINATION); 
     setListAdapter(adapter); 

     lv = getListView(); 

     registerForContextMenu(lv); 

    } 

    @Override 
    public void onListItemClick(ListView l, View v, int position, long id) { 
       // It works fine 
       // It works even after long tap instead of context menu! 
     Toast.makeText(this, "Item clicked!", Toast.LENGTH_SHORT).show(); 
    } 

    @OptionsItem 
    public void addPlace(){ 
       // It works OK too 
     startActivity(new Intent(this, PlaceEditor_.class)); 

    } 

    public void editPlace() { 
     // ...skipped for brevity... 
    } 

    public void deletePlace() { 
      // ...skipped... 
    } 

    @Override 
    public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) { 
       // This isn't ever called! 
     super.onCreateContextMenu(menu, v, menuInfo); 

     MenuInflater inflater = getMenuInflater(); 
     inflater.inflate(R.menu.place_options, menu); 
    } 

    @Override 
    public boolean onContextItemSelected(MenuItem item) { 
     // ...skipped... 
    } 

} 

有人可以告訴我這裏有什麼問題嗎?感謝您的提前。

回答

5

我明白了!這是我自己的錯誤:.init()方法必須註釋爲@AfterViews,而不是@AfterInject。它的工作原理是這樣的:ListActivity有一個默認的的ListView創建的時候,那麼我的豆PlacesDB注入,將觸發@AfterInject方法後,即.init()其中默認的ListView註冊了上下文菜單, R.layout.places被設置爲活動內容視圖與另一的ListView這是註冊後!因此,改變註釋@AfterViews使得.init().setContentView(R.layout.places),然後我自己的ListView從佈局註冊上下文菜單運行,一切都開始工作:)