一.在配置文件采用自定义Style方法去除Actionbar
<resources> <style name="MyTheme" parent="Theme.AppCompat.Light.DarkActionBar"> <!-- Customize your theme here. --> <item name="colorPrimary">@color/colorPrimary</item> <item name="colorPrimaryDark">@color/colorPrimaryDark</item> <item name="colorAccent">@color/colorAccent</item> <!--去除Actionbar--> <item name="windowActionBar">false</item> <item name="windowNoTitle">true</item> <!--toolbar菜单颜色设置--> <item name="android:textColorSecondary">#ffff</item> </style> </resources>
二.XML文件中添加Toolbar
<android.support.v7.widget.Toolbar android:id="@+id/tb_id" android:layout_width="match_parent" android:layout_height="?android:attr/actionBarSize" android:background="?attr/colorPrimary" app:titleTextColor="@color/colorwhite" ></android.support.v7.widget.Toolbar>
三.在java代码中添加Toolbar
public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); initTools(); } //添加Toolbar private void initTools() { android.support.v7.widget.Toolbar mtoolbar=findViewById(R.id.tb_id);
//设置Toolbar菜单点击事件 mtoolbar.setOnMenuItemClickListener(new Toolbar.OnMenuItemClickListener() { @Override public boolean onMenuItemClick(MenuItem menuItem) { switch (menuItem.getItemId()) { case R.id.one: { Toast.makeText(MainActivity.this, "我是1", Toast.LENGTH_SHORT).show(); break; } case R.id.two: { Toast.makeText(MainActivity.this, "我是2", Toast.LENGTH_SHORT).show(); break; } case R.id.three: { Toast.makeText(MainActivity.this, "我是3", Toast.LENGTH_SHORT).show(); break; } } return true; } }); setSupportActionBar(mtoolbar); }
// 创建Toolbar菜单
//R.menu.menu是一个定义菜单选项的XMl文件,在第四步中说明 @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.menu,menu); return super.onCreateOptionsMenu(menu); }
}
四.menu选项菜单选项设置
通过在res目录下新建menu目录,并在该目录下添加Menu resourse file(其实就是一个XML文件),然后就可以定义想要的选项.
<?xml version="1.0" encoding="utf-8"?> <menu xmlns:android="http://schemas.android.com/apk/res/android" > <item android:id="@+id/one" android:title="one" /> <item android:id="@+id/two" android:title="two" /> <item android:id="@+id/three" android:title="three" /> </menu>