1.先自定義一個繼承viewGroup的類,并重寫帶兩個參數(shù)的構(gòu)造函數(shù)
public class TitleLayout extends LinearLayout {
public TitleLayout(final Context context, @Nullable AttributeSet attrs) {
super(context, attrs);
LayoutInflater.from(context).inflate(R.layout.title,this);//LayoutInflater的from方法可以構(gòu)建一個LayoutInflater對象,然后調(diào)用inflate方法可以動態(tài)加載布局,第一個參數(shù)是布局文件,第二個參數(shù)代表添加一個父布局,這里指定為TitleLayout
Button back=findViewById(R.id.back);
TextView title=findViewById(R.id.title);
Button edit=findViewById(R.id.edit);
TypedArray attr=context.obtainStyledAttributes(attrs,R.styleable.TitleLayout);
//自定義的屬性賦值給title
if (attr!=null){
String titleName=attr.getString(R.styleable.TitleLayout_titleName);
if (!TextUtils.isEmpty(titleName)){
title.setText(titleName);
}
attr.recycle();
}
back.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
((Activity)context).finish();
}
});
edit.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
Toast.makeText(context,"您點(diǎn)擊了編輯按鈕",Toast.LENGTH_SHORT).show();
}
});
}
}
2.自定義控件的自定義的屬性,在attrs.xml文件中定義
<?xml version="1.0" encoding="utf-8"?>
<resources>
<declare-styleable name="TitleLayout">
<attr name="titleName" format="reference|string" />
</declare-styleable>
</resources>
3.自定義控件的調(diào)用,在需要自定義控件的布局文件中寫入以下代碼即可。
<com.firstlinecode.ui.TitleLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:titleName="這是自定義控件的標(biāo)題"></com.firstlinecode.ui.TitleLayout>