在我的应用程序中,我想为工具栏设置自定义菜单。我在menu_settings.xml
中定义的图标是箭头,但是当我启动应用程序时,它是一个三点菜单而不是箭头(如图中所示)。经过几个小时的研究,我仍然无法弄清楚为什么它加载这个图标而不是箭头(是的,我检查了drawable;))。感谢您提供解决方案和提示!
SettingsActivity:
public class SettingsActivity extends PreferenceActivity {
private AppCompatDelegate mDelegate;
@Override
protected void onCreate(Bundle savedInstanceState) {
getDelegate().installViewFactory();
getDelegate().onCreate(savedInstanceState);
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_settings);
Toolbar toolbar = (Toolbar) findViewById(R.id.tool_bar);
setSupportActionBar(toolbar);
Intent intent = getIntent();
boolean hasConfiguredSettings = intent.getBooleanExtra(HAS_CONFIGURED_SETTINGS, false);
if (hasConfiguredSettings) {
toolbar.setTitle("Wähle deine Linien!");
} else {
// Back button in Toolbar
toolbar.setNavigationIcon(R.drawable.abc_ic_ab_back_mtrl_am_alpha);
toolbar.setNavigationOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
onBackPressed();
}
});
}
// Display the fragment as the main content.
getFragmentManager().beginTransaction()
.replace(R.id.content, new SettingsFragment())
.commit();
}
private void setSupportActionBar(Toolbar toolbar) {
getDelegate().setSupportActionBar(toolbar);
}
private AppCompatDelegate getDelegate() {
if (mDelegate == null) {
mDelegate = AppCompatDelegate.create(this, null);
}
return mDelegate;
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
Intent intent = getIntent();
boolean hasConfiguredSettings = intent.getBooleanExtra("HAS_CONFIGURED_SETTINGS", false);
if (hasConfiguredSettings) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.menu_settings, menu);
return true;
}
return false;
}
}
menu_settings.xml:
<?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"
xmlns:tools="http://schemas.android.com/tools"
tools:context=".SettingsActivity">
<item
android:id="@+id/action_checked"
android:orderInCategory="101"
android:title="@string/configuration_action_button"
app:showAsAction="always"
android:icon="@drawable/ic_action_arrow_right"/>
</menu>
toolbar.xml:
<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.Toolbar xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_height="wrap_content"
android:layout_width="match_parent"
android:background="@color/primary"
/>
工具栏包含在:
中<include
android:id="@+id/tool_bar"
layout="@layout/toolbar" />
答案 0 :(得分:1)
您需要使用AppCompatDelegate#getMenuInflater代替Activity#getMenuInflater()。
替换以下行:
MenuInflater inflater = getMenuInflater();
与
MenuInflater inflater = getDelegate().getMenuInflater();