【问题标题】:How to add button in ActionBar(Android)?如何在 ActionBar(Android) 中添加按钮?
【发布时间】:2013-06-29 19:54:52
【问题描述】:

我想在示例右侧的操作栏中添加一个按钮,如此屏幕截图所示:

我在 onCreate 方法中得到 actionBar:

ActionBar actionBar = getActionBar();
actionBar.setDisplayHomeAsUpEnabled(true);

和后退按钮(onOptionsItemSelected 方法)如下:

public boolean onOptionsItemSelected(MenuItem item){
    Intent myIntent = new Intent(getApplicationContext(),MainActivity.class);
    startActivityForResult(myIntent, 0);
    return true;
}

如何添加按钮?

【问题讨论】:

    标签: android button android-actionbar


    【解决方案1】:

    您必须在 res/menu,override onCreateOptionsMenu 中创建一个条目并对其进行膨胀

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.yourentry, menu);
        return true;
    }
    

    菜单条目可以是:

    <menu xmlns:android="http://schemas.android.com/apk/res/android" >
        <item
            android:id="@+id/action_cart"
            android:icon="@drawable/cart"
            android:orderInCategory="100"
            android:showAsAction="always"/> 
    </menu>
    

    【讨论】:

    • 好的。那行得通。但我不明白 orderInCategory 的用法和它的值为 100。
    • 它是一个整数,表示项目在组内的“重要性”顺序。你可以改变它。只要您在菜单中有一个或两个元素,它就没有什么区别。你可以阅读它here
    • 谢谢。现在另一个问题是我在另一个活动中添加了这个菜单,但显示的是不同的按钮而不是这个。那么我该怎么做呢?
    • 哦,我知道我必须在 res/menu 下创建不同的文件才能在另一个活动中使用不同的菜单。顺便谢谢你。
    • 我们可以更改按钮的位置吗?我把它放在最右边。我可以把它放在中间吗??
    【解决方案2】:

    一个活动在其onCreateOptionsMenu() 方法中填充ActionBar。

    不要使用setcustomview(),而是像这样覆盖onCreateOptionsMenu

    @Override    
    public boolean onCreateOptionsMenu(Menu menu) {
      MenuInflater inflater = getMenuInflater();
      inflater.inflate(R.menu.mainmenu, menu);
      return true;
    }
    

    如果选择了 ActionBar 中的动作,则调用 onOptionsItemSelected() 方法。它接收选定的动作作为参数。根据此信息,您的代码可以决定要执行的操作,例如:

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
      switch (item.getItemId()) {
        case R.id.menuitem1:
          Toast.makeText(this, "Menu Item 1 selected", Toast.LENGTH_SHORT).show();
          break;
        case R.id.menuitem2:
          Toast.makeText(this, "Menu item 2 selected", Toast.LENGTH_SHORT).show();
          break;
      }
      return true;
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多