1、在XML文件中使用Toolbar,要使用全类名。
<android.support.v7.widget.Toolbar
android:id="@+id/toolbar"
android:layout_width="match_parent"
android:layout_height="@dimen/actionbar_height"
app:contentInsetLeft="0dp"
app:contentInsetStart="0dp"
app:popupTheme="@style/Theme.AppCompat.Light"
app:theme="@style/Toolbar"
/>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="@color/app_color">
<ImageView
android:id="@+id/image_view_back_login"
android:layout_width="wrap_content"
android:layout_marginLeft="16dp"
android:layout_marginStart="16dp"
android:layout_marginTop="6dp"
android:layout_height="wrap_content"
android:background="@drawable/returned">
</ImageView>
</LinearLayout>
2、核心代码
1)找到Toolbar的布局文件,转换为View
View customActionbar=View.inflate(this,R.layout.layout_my_orders_actionbar, null);
2)找到布局中的Toolbar控件
Toolbar mToolbarView = (Toolbar) findViewById(R.id.toolbar);
3)为所在的activity window设置toolbar
setSupportActionBar(mToolbarView);
4)为toolbar添加view布局
mToolbarView.addView(customActionbar, new android.app.ActionBar.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
5)为toolbar所绑定的view上的控件做相应的处理
//设置文字
TextView title = (TextView) customActionbar.findViewById(R.id.text_view_title);
title.setTextColor(getResources().getColor(R.color.normal_title_color));
title.setText("title");
//返回键
ImageView back = (ImageView) customActionbar.findViewById(R.id.image_view_back_my_order);
back.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
finish();
}
});
3、toolbar所绑定的view的布局
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="@dimen/actionbar_height">
<ImageView
android:id="@+id/image_view_back_my_order"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:background="?attr/selectableItemBackgroundBorderless"
android:clickable="true"
android:scaleType="center"
android:src="@mipmap/ic_arrow_return" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/text_view_title"
android:layout_centerInParent="true"
android:text="@string/title_activity_my_order"
android:textColor="@color/normal_title_color"
android:textSize="@dimen/title_text_size" />
</RelativeLayout>