<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:id="@+id/container" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" > <com.gjl.day_06.MyTitle android:id="@+id/myTitle" android:layout_width="match_parent" android:layout_height="wrap_content"></com.gjl.day_06.MyTitle>
</LinearLayout>
title_layout
<?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="#f00" > <Button android:id="@+id/back" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentLeft="true" android:background="#F0F" android:text="返回"/> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerInParent="true" android:gravity="center" android:text="标题" android:textColor="@android:color/white"/> <Button android:id="@+id/tijiao" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentRight="true" android:text="提交"/> </RelativeLayout>
package com.gjl.day_06; import android.content.Context; import android.util.AttributeSet; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.widget.Button; import android.widget.RelativeLayout; import android.widget.Toast; /** * Created by Administrator on 2017/12/29 0029. */ public class MyTitle extends RelativeLayout implements View.OnClickListener{ private Context mContext; private static final String TAG = "MyTitle"; public MyTitle(Context context) { this(context, null); } public MyTitle(Context context, AttributeSet attrs) { this(context, attrs, 0); } public MyTitle(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); //初始化布局 LayoutInflater inflater = LayoutInflater.from(context); //必须依赖父布局 // View view = inflater.inflate(R.layout.title_layout, null); View view = inflater.inflate(R.layout.title_layout, this,true); //找到控件 Button back = view.findViewById(R.id.back); Button tijiao = view.findViewById(R.id.tijiao); //设置点击事件 back.setOnClickListener(this); tijiao.setOnClickListener(this); mContext = context; } @Override public void onClick(View v) { switch (v.getId()){ case R.id.back: Log.d(TAG, "onClick() returned: " + "fanhui-----"); Toast.makeText(mContext,"返回",Toast.LENGTH_SHORT).show(); break; case R.id.tijiao: Log.d(TAG, "onClick() returned: " + "提交---"); Toast.makeText(mContext,"提交",Toast.LENGTH_SHORT).show(); break; } } }