1. 定义布局文件,在layout下新建title_bar_view.xml
<?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="48dp"android:background="@drawable/bg_top_bar" ><ImageViewandroid:id="@+id/bar_back"android:layout_width="48dp"android:layout_height="48dp"android:scaleType="center"android:src="@drawable/btn_back_selector" /><TextViewandroid:id="@+id/bar_title"android:layout_width="match_parent"android:layout_height="match_parent"android:layout_alignParentTop="true"android:layout_centerHorizontal="true"android:layout_marginLeft="48dp"android:layout_marginRight="48dp"android:gravity="center"android:text="Title"android:textColor="#FFFFFFFF"android:textSize="24sp"android:textStyle="normal" /><TextViewandroid:id="@+id/bar_action"android:layout_width="48dp"android:layout_height="48dp"android:layout_alignParentRight="true"android:layout_centerVertical="true"android:gravity="center"android:text="action"android:textColor="#FFFFFFFF"android:textSize="18sp"android:textStyle="normal"android:visibility="gone" /></RelativeLayout>
相关资源,在drawable下新建btn_back_selector.xml
<?xml version="1.0" encoding="utf-8"?> <selector xmlns:android="http://schemas.android.com/apk/res/android"><item android:drawable="@drawable/action_button_back_pressed" android:state_pressed="true"/><item android:drawable="@drawable/action_button_back_normal"/> </selector>
2. 自定义View继承自RelativeLayout
public class TitleBar extends RelativeLayout{private ImageView ivBack;private TextView tvTitle;private TextView tvAction;public TitleBar(Context context) {this(context,null);}public TitleBar(Context context, AttributeSet attrs) {super(context, attrs);View view = View.inflate(context, R.layout.title_bar_view, this);ivBack = (ImageView) view.findViewById(R.id.bar_back);tvTitle = (TextView) view.findViewById(R.id.bar_title);tvAction = (TextView) view.findViewById(R.id.bar_action);}public void setBackVisibility(boolean show) {ivBack.setVisibility(show ? View.VISIBLE : View.INVISIBLE);}public void setTitle(String title) {tvTitle.setText(title);}public ImageView getIvBack() {return ivBack;}public void setIvBack(ImageView ivBack) {this.ivBack = ivBack;}public TextView getTvTitle() {return tvTitle;}public void setTvTitle(TextView tvTitle) {this.tvTitle = tvTitle;}public TextView getTvAction() {return tvAction;}public void setTvAction(TextView tvAction) {this.tvAction = tvAction;} }