为什么要写自定义布局:
1.在实现大量重复的子按键或者子布局时,如果一个一个去复写工作量庞大,就需要创建自定义布局直接导入布局里,可以节省大量的时间
创建自定义布局的步骤:
1.编写一个自定义xml布局
2.将这个自定义xml布局实例化成Java布局类(继承布局类实现),在布局类中直接添加功能
3.将这个类写入父类的xml布局文件里
步骤1:编写一个自定义xml布局
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="wrap_content" android:layout_height="wrap_content"> <Button android:id="@+id/demobutton" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="这是一个实验按键"/> </LinearLayout>
步骤2:将这个自定义xml布局实例化成Java布局类(继承布局类实现)
package com.example.prize.mydemo1; import android.content.Context; import android.util.AttributeSet; import android.view.LayoutInflater; import android.view.View; import android.widget.Button; import android.widget.LinearLayout; import android.widget.Toast; /** * Created by prize on 2018/4/8. * 实例化一个自定义布局,并且在布局中添加按键功能 */ public class MyLayout extends LinearLayout { public MyLayout(Context context, AttributeSet attrs){ super(context,attrs); LayoutInflater.from(context).inflate(R.layout.activity_mylayout,this); //剪裁实例化mylayout布局 Button button =(Button)findViewById(R.id.demobutton); button.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { Toast.makeText(getContext(),"点击实现了试验按键",Toast.LENGTH_SHORT).show(); } }); } }
步骤3:将这个类写入父类的xml布局文件里
<?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" android:layout_width="match_parent" android:layout_height="match_parent"> <!--添加自定义布局--> <!--注意布局路径是需要全部包名路径--> <com.example.prize.mydemo1.MyLayout android:layout_width="match_parent" android:layout_height="wrap_content"> </com.example.prize.mydemo1.MyLayout> </LinearLayout>