【问题标题】:Can't add Button to Android ActionBar API 21无法将按钮添加到 Android ActionBar API 21
【发布时间】:2015-03-24 15:01:20
【问题描述】:

我想在我的 Android ActionBar 中添加一个搜索按钮,为此我遵循了this 的回答。唯一发生的事情是“搜索”按钮被添加到菜单本身而不是 ActionBar(见下面的截图)。

这是我的 search.java(显示搜索按钮的活动):

public class search extends ActionBarActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    getWindow().requestFeature(Window.FEATURE_ACTION_BAR);
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_search);
}


@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    MenuInflater inflater=getMenuInflater();
    inflater.inflate(R.menu.menu_search, menu);
    return super.onCreateOptionsMenu(menu);
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    int id = item.getItemId();

    //noinspection SimplifiableIfStatement
    if (id == R.id.action_settings) {
        return true;
    }

    return super.onOptionsItemSelected(item);
}
}

这是我的 menu_search.xml

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

感谢任何帮助!提前致谢!

【问题讨论】:

  • The only thing that happens is that the "Search" button is added to the menu itself 因为这正是你所做的。没有按钮被添加到操作栏中。如果你想添加一个按钮,你应该使用Toolbar 而不是Actionbar
  • @tyczj:嗯,不,您可以将操作栏项目添加到操作栏就好了。
  • @CommonsWare 我从来没有在操作栏中看到Button 我见过ActionButtons OP 没有说
  • @tyczj:如果您查看代码,OP 似乎正在寻找操作栏项目。我同意问题的标题令人困惑。

标签: java android android-actionbar


【解决方案1】:

您正在使用appcompat-v7。您需要将 android:showAsAction 属性更改为 app:showAsAction 属性,并定义 app 命名空间 (xmlns:app="http://schemas.android.com/apk/res-auto")。

这会给你类似的东西:

<menu xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto">
<item
    android:title="search"
    android:id="@+id/action_search"
    android:icon="@drawable/searchicon"
    android:orderInCategory="100"
    app:showAsAction="always"/>
</menu>

另外,您可能不需要android:orderInCategory

【讨论】:

    【解决方案2】:

    你应该做的是添加:

    <?xml version="1.0" encoding="utf-8"?>
    <menu xmlns:android="http://schemas.android.com/apk/res/android"
          xmlns:app="http://schemas.android.com/apk/res-auto" >
    <item 
        android:id="@+id/action_search"
        android:title="search"
        app:showAsAction="always"
        android:actionViewClass="android.widget.SearchView"/>
    

    【讨论】:

      猜你喜欢
      • 2013-06-29
      • 2014-03-18
      • 1970-01-01
      • 1970-01-01
      • 2011-12-29
      • 1970-01-01
      • 1970-01-01
      • 2016-03-16
      • 2015-06-26
      相关资源
      最近更新 更多