向操作栏添加操作

时间:2014-07-20 17:37:50

标签: android android-actionbar

所以我根据Android开发培训完成了我想做的事情,但仍然无法看到操作栏上的操作,而是在溢出菜单中。

<menu xmlns:android="http://schemas.android.com/apk/res/android" >

<!-- Search, should appear as action button -->
<item
    android:id="@+id/action_search"
    android:icon="@drawable/ic_action_search"
    android:showAsAction="ifRoom"
    android:title="@string/action_search"/>
<!-- Settings, should always be in the overflow -->
<item
    android:id="@+id/action_settings"
    android:showAsAction="never"
    android:title="@string/action_settings"/>

</menu>



public class MainActivity extends ActionBarActivity {

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


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

@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();
    if (id == R.id.action_settings) {
        return true;
    }
    return super.onOptionsItemSelected(item);
}
}

我还设置了:

 <uses-sdk
    android:minSdkVersion="11"
    android:targetSdkVersion="21" />

我现在该怎么办?

2 个答案:

答案 0 :(得分:1)

这是一个错误。您应该应用另一个命名空间:

<menu xmlns:android="http://schemas.android.com/apk/res/android" 
      xmlns:app="http://schemas.android.com/apk/res-auto">

<!-- Search, should appear as action button -->
<item
    android:id="@+id/action_search"
    android:icon="@drawable/ic_action_search"
    app:showAsAction="ifRoom"
    android:title="@string/action_search"/>
<!-- Settings, should always be in the overflow -->
<item
    android:id="@+id/action_settings"
    android:showAsAction="never"
    android:title="@string/action_settings"/>

</menu>

答案 1 :(得分:0)

您可以随时通过将myapp:showAsAction="ifRoom"更改为myapp:showAsAction="always"

来强制显示菜单条目

不要忘记在xmlns:myapp="http://schemas.android.com/apk/res-auto"

之前定义您的app命名空间

从文档引用命名空间更改:

The showAsAction attribute above uses a custom namespace defined in the tag. This is necessary when using any XML attributes defined by the support library, because these attributes do not exist in the Android framework on older devices. So you must use your own namespace as a prefix for all attributes defined by the support library.

也许您的应用名称太大,这就是菜单条目没有出现的原因。