我已将应用程序的主题设置为NoActionBar并已实现appcompatv7工具栏。 但是,工具栏不会显示menu_main.xml文件中明确提到的项目的任何图标。 即使默认显示的溢出图标也不会出现在工具栏上。
menu_main.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.codesters.materialdesign.MainActivity">
<item
android:id="@+id/action_settings"
android:orderInCategory="100"
android:title="@string/action_settings"
app:showAsAction="never" />
<item
android:id="@+id/action_navigate"
android:orderInCategory="200"
android:title="@string/next"
app:showAsAction="always"
android:icon="@drawable/ic_action_next_item"/>
</menu>
styles.xml文件:
<resources>
<!-- Base application theme. -->
<style name="AppTheme" parent="AppTheme.Base">
</style>
<style name="AppTheme.Base" parent="Theme.AppCompat.Light.NoActionBar">
<item name="colorPrimary">@color/colorPrimary</item>
<item name="colorPrimaryDark">@color/colorPrimaryDark</item>
<item name="colorAccent">@color/colorAccent</item>
</style>
<style name="CustomToolBarTheme" parent="ThemeOverlay.AppCompat.Light">
<item name="android:textColorPrimary">#FFFF</item>
<item name="android:textColorSecondary">#FFFF</item>
</style>
</resources>
MainActivity文件:
public class MainActivity extends ActionBarActivity {
private Toolbar toolbar;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
toolbar = (Toolbar) findViewById(R.id.app_bar);
setSupportActionBar(toolbar);
}
@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) {
Toast.makeText(this, "You have clicked" + item.getTitle(), Toast.LENGTH_SHORT);
}
if (id == R.id.action_navigate) {
Toast.makeText(this, "You have clicked" + item.getTitle(), Toast.LENGTH_SHORT);
}
return super.onOptionsItemSelected(item);
}
}
答案 0 :(得分:2)
编写onCreateOptionsMenu(Menu menu)
方法并对您在xml中创建的菜单进行充气。
然后你的代码看起来像。
@Override
public boolean onCreateOptionsMenu(Menu menu){
getMenuInflater().inflate(R.menu.menu_main, 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) {
Toast.makeText(this, "You have clicked" + item.getTitle(), Toast.LENGTH_SHORT);
}
if (id == R.id.action_navigate) {
Toast.makeText(this, "You have clicked" + item.getTitle(), Toast.LENGTH_SHORT);
}
return super.onOptionsItemSelected(item);
}