Android自定義組件,并把自定義組件和自定義xml布局文件關(guān)聯(lián)

前言

在開發(fā)自定義view時,往往需要綁定xml布局文件,那具體怎么做呢?

自定義view和xml布局文件關(guān)聯(lián)的思路是:在自定義view的構(gòu)造函數(shù)中,通過LayoutInflater.from(context).inflate(R.layout.test_layout, this)關(guān)聯(lián)xml布局文件。具體代碼如下

1、代碼

自定義布局——xml代碼(test_layout.xml)

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <TextView
        android:id="@+id/tv_title"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />

</LinearLayout>

自定義組件——Java代碼(TestView)

public class TestView extends LinearLayout {

    public TestView(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        init(context);
    }

    /**
     * 初始化組件
     * @param context
     */
    private void init(Context context) {

        //加載布局文件到此自定義組件
        //注意:第二個參數(shù)需填this,表示加載text_layout.xml到此自定義組件中。如果填null,則不加載,即不會顯示text_layout.xml中的內(nèi)容
        View view = LayoutInflater.from(context).inflate(R.layout.test_layout, this);

        //動態(tài)設置自定義xml中TextView的顯示內(nèi)容
        TextView title = view.findViewById(R.id.tv_title);
        title.setText("我是自定義標題");
    }
}

調(diào)用代碼(activity_main.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"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.fireflyh.demo.MainActivity"
    android:orientation="vertical">

    <com.fireflyh.demo.widget.TestView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"></com.fireflyh.demo.widget.TestView>

</LinearLayout>

正文結(jié)束


2、坑

錯誤重現(xiàn):

LayoutInflater.from(context).inflate(R.layout.test_layout, this);

寫成了

LayoutInflater.from(context).inflate(R.layout.test_layout, null);

現(xiàn)象:自定義xml中的內(nèi)容不顯示在自定義組件中。

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

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