所謂組合控件肃续,指的是把系統(tǒng)現(xiàn)有的控件組合在一起形成一個(gè)新控件幕帆。這里我們自定義一個(gè)LinearLayout控件,LinearLayout控件中又含有RelativeLayout控件葡幸,RelativeLayout控件中有TextView控件和RadioGroup控件了袁。布局如下:
combined_view.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="wrap_content"
android:orientation="horizontal">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<TextView
android:id="@+id/tv"
android:layout_marginStart="10dp"
android:layout_centerVertical="true"
android:layout_alignParentStart="true"
android:text="你的性別是朗恳?"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<RadioGroup
android:id="@+id/rg"
android:layout_centerVertical="true"
android:layout_alignParentEnd="true"
android:layout_marginEnd="10dp"
android:layout_gravity="center_vertical"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<RadioButton
android:id="@+id/bt_01"
android:text="男"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
<RadioButton
android:id="@+id/bt_02"
android:text="女"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
</RadioGroup>
</RelativeLayout>
</LinearLayout>
控件的布局有了,需要把當(dāng)前布局添加到控件樹中载绿。
CustomCombinedView
創(chuàng)建類CustomCombinedView,繼承自LinearLayout油航,在構(gòu)造方法中進(jìn)行初始化
public CustomCombinedView(Context context) {
this(context,null);
}
public CustomCombinedView(Context context, @Nullable AttributeSet attrs) {
this(context, attrs,0);
}
public CustomCombinedView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
View view = View.inflate(context, R.layout.combined_view, this);
TextView textView = view.findViewById(R.id.tv);
RadioGroup radioGroup = view.findViewById(R.id.rg);
textView.setText("不是默認(rèn)的字符串");
textView.setTextColor(Color.RED);
radioGroup.setOnCheckedChangeListener(this);
}
首先通過View.inflate將當(dāng)前的布局添加到控件樹中去崭庸,然后通過返回的View獲取布局中的子控件。特意選了RadioGroup谊囚,這里可以通過對RadioGroup的監(jiān)聽加一些邏輯:RadioGroup setOnCheckedChangeListener:
@Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
if (checkedId == R.id.bt_01) {
Toast.makeText(getContext(),"I am man.",Toast.LENGTH_SHORT).show();
} else if (checkedId == R.id.bt_02) {
Toast.makeText(getContext(),"I am women.",Toast.LENGTH_SHORT).show();
}
}
點(diǎn)擊不同的RadioButton會(huì)彈不同內(nèi)容的Toast怕享。
總結(jié)
自定義組合控件大致分為以下幾步:
- 書寫布局
- 將布局以代碼的方式添加到控件樹中,并得到對應(yīng)的View對象
- 通過View對象可以獲得子控件的Id镰踏,通過Id可以自定義處理邏輯函筋。