1 . 创建布局 actionbar_custom.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="60dp"
android:background="#8ab3f4"
android:orientation="horizontal">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_vertical"
android:layout_marginLeft="10dp"
android:textSize="20sp"
android:textStyle="bold"
android:textColor="#ffffff"
android:text="ListDemo"/>
</LinearLayout>
2 . activity 中设置 actionbar
ActionBar actionBar = getSupportActionBar();
View actionbarView = LayoutInflater.from(this).inflate(R.layout.actionbar_custom,null);
ActionBar.LayoutParams layoutParams = new ActionBar.LayoutParams(ActionBar.LayoutParams.MATCH_PARENT,
ActionBar.LayoutParams.MATCH_PARENT);
layoutParams.gravity = Gravity.CENTER_HORIZONTAL |Gravity.CENTER_HORIZONTAL;
actionBar.setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM);
actionBar.setDisplayShowCustomEnabled(true);
actionBar.setDisplayShowHomeEnabled(true);
actionBar.setDisplayShowTitleEnabled(true);
actionBar.setCustomView(actionbarView, layoutParams);
Toolbar parent =(Toolbar) actionbarView.getParent();
parent.setContentInsetsAbsolute(0,0);
3 . actionbar显示返回按钮
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setHomeButtonEnabled(true);
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
this.finish(); // back button
return true;
}
return super.onOptionsItemSelected(item);
}