0

我使用 SherlockListActivity,我在创建活动后第一次单击它时创建了带有一个项目及其 clickListener 的 ActionBar,不调用 onMenuItemClick,但是在第一次单击后的每次单击中,都可以正常工作

为什么 ?

private void BuildTopActionBar() {
        BitmapDrawable bg = (BitmapDrawable) getResources().getDrawable(
                R.drawable.ic_action_bg);
        bg.setTileModeXY(TileMode.REPEAT, TileMode.REPEAT);
        getSupportActionBar().setBackgroundDrawable(bg);

        this.getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        this.getSupportActionBar().setHomeButtonEnabled(true);
        this.getSupportActionBar().setTitle("bookmarks");
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
        case android.R.id.home:
            // This is called when the Home (Up) button is pressed in the Action Bar.
            finish();
            return true;
        case add_bookmark_item:
            // add
            item.setOnMenuItemClickListener(new OnMenuItemClickListener() {

                public boolean onMenuItemClick(MenuItem item) {
                    customAmbilWarnaDialog dialog = new customAmbilWarnaDialog(
                            BookMarksActivity.this, 0xffffffff,
                            new OnAmbilWarnaListener() {

                                public void onCancel(
                                        customAmbilWarnaDialog dialog) {
                                }

                                public void onOk(customAmbilWarnaDialog dialog,
                                        int color, String name, int hasName) {
                                    myDbHelper.AddNewBookmark(name,
                                            currentPageNum, color, hasName);
                                    // code
                                    lv.smoothScrollToPosition((lv.getCount() - 1));
                                }
                            });
                    dialog.show();                  
                    return true;
                }
            });

        }

        return super.onOptionsItemSelected(item);

    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {

        menu.add(0, add_bookmark_item, 0, "add bookmark")
                .setIcon(R.drawable.bookmark_add)
                .setShowAsAction(
                        MenuItem.SHOW_AS_ACTION_COLLAPSE_ACTION_VIEW
                                | MenuItem.SHOW_AS_ACTION_ALWAYS);

        return true;
    }
4

1 回答 1

1

原因是你在方法中调用item.setOnMenuItemClickListener(new OnMenuItemClickListener() {...onOptionsItemSelected()

这意味着它将在您第一次单击时设置menuItem(然后在每次单击时重置),并且其中的代码只有在您至少单击一次后才会运行。

要么调用它,onCreateOptionsMenu()要么简单地将代码从onMenuItemClick()开关/外壳移到

于 2013-01-16T13:40:57.770 回答