Android App中的操作栏上未显示操作项/图标

时间:2014-07-21 19:08:42

标签: java android android-actionbar

我正在尝试在操作栏上执行搜索操作。我已经设置了一个图标并将showAsAction设置为always,但它仍然总是显示在溢出菜单中。如何将其显示在操作栏上?谢谢!

活动

public class MainActivity extends ActionBarActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    setTitle("Add");
    getMenuInflater().inflate(R.menu.main, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    int id = item.getItemId();
    if (id == R.id.action_settings) {
        Toast.makeText(getApplicationContext(), "Settings",
                   Toast.LENGTH_LONG).show();
        return true;
    }
    if (id == R.id.action_search) {
        Toast.makeText(getApplicationContext(), "Search",
                   Toast.LENGTH_LONG).show();
        return true;
    }
    return super.onOptionsItemSelected(item);
}

}

菜单XML文件

<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
tools:context="com.example.testtabs.MainActivity" >

<item
    android:id="@+id/action_settings"
    android:orderInCategory="100"
    android:title="@string/action_settings"
    app:showAsAction="never"/>
<item
    android:id="@+id/action_search"
    android:actionViewClass="android.support.v7.widget.SearchView"
    android:icon="@drawable/ic_search"
    android:showAsAction="always"
    android:title="@string/title_search"/>

</menu>

capture

2 个答案:

答案 0 :(得分:0)

删除

android:actionViewClass="android.support.v7.widget.SearchView"

或删除onOptionsItemSelected中action_search的case语句。执行其中任何一项都会显示图标。

如果要使用SearchView,则回调的处理方式与onOptionsItemSelected不同。

此处的文档:http://developer.android.com/guide/topics/ui/actionbar.html#ActionView

答案 1 :(得分:0)

只需更改应用:showAsAction而不是 android :showAsAction

<menu xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    tools:context="com.example.testtabs.MainActivity" >

    <item
        android:id="@+id/action_settings"
        android:orderInCategory="100"`enter code here`
        android:title="@string/action_settings"
        app:showAsAction="never"/>
    <item
        android:id="@+id/action_search"
        android:actionViewClass="android.support.v7.widget.SearchView"
        android:icon="@drawable/ic_search"
        app:showAsAction="always"
        android:title="@string/title_search"/>

    </menu>