自定義控件

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>
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容