10.Android开发笔记:布局控件(五) 自定义控件 1.引入布局 2.自定义 控件

10.Android开发笔记:布局控件(五) 自定义控件
1.引入布局
2.自定义 控件

第一步:创建布局文件 activity_back.xml
第二布:已入布局:
java <include layout="@layout/activity_back"/>

2.自定义 控件

创建 布局文件 title.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:andro
  android:layout_width="match_parent"
  android:layout_height="wrap_content"
  android:background="@drawable/ic_launcher_background">

  <Button android:
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:layout_gravity="center"
      android:text="返回" />

  <TextView android:
      android:layout_width="0dp"
      android:layout_height="wrap_content"
      android:layout_weight="1"
      android:gravity="center"
      android:layout_gravity="center"
      android:background="#bbb"
      android:text="标题" />

  <Button android:
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:layout_gravity="center"
      android:text="设置"/>
</LinearLayout>

创建java类:TitleLayout


public class TitleLayout extends LinearLayout {

    public TitleLayout(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);

        LayoutInflater.from(context).inflate(R.layout.title,this);//1

        Button btn_goBack = findViewById(R.id.t_btn_goBack);
        Button btn_detail = findViewById(R.id.bt_btn_detail);
        btn_goBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ((Activity)getContext()).finish();//2
            }
        });

        btn_detail.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Toast.makeText(getContext(),"详情",Toast.LENGTH_LONG).show();
            }
        });
    }
}

使用自定义控

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:andro
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

  <!--  <include layout="@layout/activity_back"/>-->
   <!-- <include layout="@layout/title"/>-->

  <com.example.customercontroller.myctrl.TitleLayout
      android:layout_width="match_parent"
      android:layout_height="53dp" />

</LinearLayout>