為什么要寫自定義布局:
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>
