我已经为Lollipop创建了一个工具栏,但我似乎无法弄清楚如何在工具栏中添加溢出按钮.我不打算使用v7 appcompat工具栏,因为我想明确使用工具栏小部件.我希望它看起来像这样:
main_activity.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:fab="http://schemas.android.com/apk/res-auto" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical"> <Toolbar xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/toolbar" android:layout_width="match_parent" android:layout_height="112dp" android:elevation="4dp" android:layout_alignParentTop="true" android:minHeight="?android:attr/actionBarSize" android:background="?android:attr/colorPrimary" android:gravity="bottom" android:paddingBottom="16dp"/> </RelativeLayout>
主要课程
@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_quotebook); getWindow().addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS); getWindow().setStatusBarColor(getResources().getColor(R.color.primary_dark)); getWindow().setNavigationBarColor(getResources().getColor(R.color.primary_dark)); initToolbar(); } private void initToolbar() { mToolbar = (Toolbar) findViewById(R.id.toolbar); mToolbar.setTitleTextColor(Color.WHITE); mToolbar.setTitle(R.string.app_shortname); mToolbar.showOverflowMenu(); } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.menu_overflow,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(); //noinspection SimplifiableIfStatement if (id == R.id.action_settings) { return true; } return super.onOptionsItemSelected(item); }
menu.xml文件
<menu xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto"> <item android:id="@+id/action_settings" android:orderInCategory="100" android:title="@string/action_settings" android:showAsAction="always" android:visible="true"/> </menu>
解决方法
如果你想在溢出菜单中添加项目,你应该永远设置为android:showAsAction.如果总是设置该项目将是工具栏中的图标.
像这样编辑menu.xml:
<menu xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto"> <item android:id="@+id/action_settings" android:orderInCategory="100" android:title="@string/action_settings" android:showAsAction="never" android:visible="true" /> </menu>
你还需要调用setActionBar().像这样编辑initToolbar():
private void initToolbar() { mToolbar = (Toolbar) findViewById(R.id.toolbar); mToolbar.setTitleTextColor(Color.WHITE); mToolbar.setTitle("gnappo"); mToolbar.showOverflowMenu(); setActionBar(mToolbar); }