ListActivity中的AndroidAnnotations和上下文菜单

时间:2012-07-10 18:02:29

标签: android contextmenu listactivity android-annotations

我的活动继承自 ListActivity 并使用AndroidAnnotations。虽然.onListItemClick工作正常,但列表项的上下文菜单根本不会显示,甚至不会调用.onCreateContextMenu,但在长按到列表项后会.onListItemClick触发。这是我的代码:

@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...
    }

}

有人能告诉我这里有什么问题吗?谢谢你的进步。

1 个答案:

答案 0 :(得分:5)

我明白了!这是我自己的错误:.init()方法必须注释为@AfterViews,而不是@AfterInject。它的工作原理如下: ListActivity 在创建时有一个默认的 ListView ,然后注入我的bean PlacesDB ,然后触发@AfterInject方法,即.init(),其中默认 ListView 已注册上下文菜单,之后 <{em>} R.layout.places已设置作为另一个 ListView 的活动的内容视图,已注册!因此,将注释更改为@AfterViews会使.init() .setContentView(R.layout.places)之后运行,然后从布局中为我自己的 ListView 注册上下文菜单,一切都开始工作:)