Toolbar的使用
1.添加依赖包
implementation 'com.android.support:appcompat-v7:25.0.1'
2.确保Activity可以扩展AppCompatActivity
public class MainActivity extends AppCompatActivity {
}
3.修改App的主题
<style name="AppBaseTheme" parent="Theme.AppCompat.Light.NoActionBar"></style>
<style name="AppTheme" parent="AppBaseTheme"></style>
4.在Activity布局中添加一个Toolbar
<android.support.v7.widget.Toolbar
android:id="@+id/toolbar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="@color/colorPrimaryDark"
app:popupTheme="@style/ToolbarPopupTheme"
app:theme="@style/ThemeOverlay.AppCompat.Dark"
app:titleTextColor="@android:color/white" />
app:popupTheme="@style/ToolbarPopupTheme"
在style中添加主题
<style name="ToolbarPopupTheme" parent="@style/ThemeOverlay.AppCompat.Light">
<item name="android:textColor">@color/colorPrimary</item>
</style>
5.Activity中进行设置
private Toolbar toolbar;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
init();
}
private void init() {
toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
}
ToolBar的Action操作
ToolBar的一大亮点之一就是允许添加很多的Action动作在其上 1.添加一个Action按钮 在res下新建menu资源文件夹,然后在menu文件夹中创建菜单栏按钮布局layout_menu.xml文件
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">
<item
android:id="@+id/item1"
android:title="title1" />
<item
android:id="@+id/item2"
android:title="title2" />
<item
android:id="@+id/item3"
android:title="title3"/>
<item
android:id="@+id/item4"
android:title="title4"/>
<item
android:id="@+id/item5"
android:title="title5"/>
</menu>
Activity中操作ToolBar的Action
初始化menue的布局文件:
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater menuInflater = getMenuInflater();
menuInflater.inflate(R.menu.layout_menu, menu);
return true;
}
控制menu中item的点击事件:
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.item1:
Toast.makeText(this, "title1", Toast.LENGTH_SHORT).show();
break;
case R.id.item2:
Toast.makeText(this, "title2", Toast.LENGTH_SHORT).show();
break;
case R.id.item3:
Toast.makeText(this, "title3", Toast.LENGTH_SHORT).show();
break;
case R.id.item4:
Toast.makeText(this, "title4" , Toast.LENGTH_SHORT).show();
break;
case R.id.item5:
Toast.makeText(this, "title5", Toast.LENGTH_SHORT).show();
break;
}
return super.onOptionsItemSelected(item);
}
测试结果如下:
|