public class TitleBarView extends LinearLayout { private TextView tvSubmit; public TitleBarView(Context context) { this(context, null); } public TitleBarView(Context context, @Nullable AttributeSet attrs) { this(context, attrs, 0); } public TitleBarView(final Context context, @Nullable AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); LayoutInflater.from(context).inflate(R.layout.title, this); TextView tvBack = findViewById(R.id.tvBack); TextView tvTitle = findViewById(R.id.tvTitle); tvSubmit = findViewById(R.id.tvSubmit); tvBack.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { Toast.makeText(context, "返回", Toast.LENGTH_SHORT).show(); } }); } public void setSubmitClick(OnClickListener onClickListener) { tvSubmit.setOnClickListener(onClickListener); } }继承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="40dp" android:background="#ff3660"> <TextView android:id="@+id/tvBack" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerVertical="true" android:text="返回" /> <TextView android:id="@+id/tvTitle" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerInParent="true" android:text="标题" /> <TextView android:id="@+id/tvSubmit" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentRight="true" android:layout_centerVertical="true" android:text="提交" /> </RelativeLayout>