为什么onMenuItemSelected没有回应???与ActionBar

时间:2012-12-20 04:39:35

标签: android actionbarsherlock

我试图通过onMenuItemSelected在我的Activity中使用ActionBarSherlock制作一个Intent / Toast。但我已经在网络中插入代码,但它没有回应。请告诉我错误的代码在哪里???

这是我的代码

public boolean onCreateOptionsMenu(Menu menu) { 
    SubMenu sub = menu.addSubMenu("more");
    MenuItem ShareButton = sub.getItem();
    ShareButton.setIcon(R.drawable.more);
    ShareButton.setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS| MenuItem.SHOW_AS_ACTION_WITH_TEXT);
    MenuInflater inflater = getSupportMenuInflater();
    inflater.inflate(R.menu.activity_home, sub);

    return true;

}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle item selection
    switch (item.getItemId()) {

    case R.id.menu_item_account:
            Toast.makeText(myContext, "You Choosed Account",Toast.LENGTH_SHORT).show();

            return true;
        case R.id.menu_item_setting:
            Toast.makeText(myContext, "You Choosed Setting", Toast.LENGTH_SHORT).show();

            return true;
        case R.id.menu_item_exit:
            Toast.makeText(myContext, "You Choosed Exit", Toast.LENGTH_SHORT).show();
            finish();
            return true;
        default:
            return super.onOptionsItemSelected(item);
    }
}

解决方案

这是我的新代码。只需删除OnOptionMenuSelected方法,然后使用onMenuItemSelected:

@覆盖     public boolean onMenuItemSelected(int featureId,MenuItem item){

    int itemId = item.getItemId();
    switch (itemId) {
    case android.R.id.home:
        finish();
        break;
    case R.id.menu_item_account:
        Toast.makeText(myContext, "Anda memilih Account",
                Toast.LENGTH_SHORT).show();
        setContentView(R.layout.account_contoh_layout);
        return true;
    case R.id.menu_item_setting:
        Toast.makeText(myContext, "Anda memilih Setting",
                Toast.LENGTH_SHORT).show();
        setContentView(R.layout.settings_contoh_layout);
        return true;

    }

    return true;
}

@覆盖     public boolean onCreateOptionsMenu(菜单菜单){

    // Used to put dark icons on light action bar
    SubMenu sub = menu.addSubMenu("");

    MenuItem ShareButton = sub.getItem();
    ShareButton.setIcon(R.drawable.ic_more);
    ShareButton.setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS
            | MenuItem.SHOW_AS_ACTION_WITH_TEXT);
    MenuInflater inflater = getSupportMenuInflater();
    inflater.inflate(R.menu.activity_home, sub);

    return true;

}

0 个答案:

没有答案