按照慣例,先上圖:

類似這樣的n選一的需求是很常見(jiàn)的,用原生的 RadioGroup 幾乎無(wú)法實(shí)現(xiàn),那么就需要一個(gè)類似功能 RadioGroup ,可以幫我們管理選中項(xiàng)狀態(tài)(并且支持設(shè)置單選和多選),同時(shí)能方便的自定義里面子項(xiàng)的UI布局,要是還能像 list 一樣支持用優(yōu)雅的 adapter 模式設(shè)置內(nèi)容和 layout 就更好了。
于是:
引入
compile 'com.yinzihao:YinLayout:{latest-version}'
使用指南
CommonCheckableGroup
多選或單選項(xiàng)的父布局,類似于{@link android.widget.RadioGroup}。
直接子 view 需要實(shí)現(xiàn){@link Checkable}接口或利用框架中的{@link CheckableTag}(事實(shí)上是一個(gè)實(shí)現(xiàn)了{@link Checkable}接口的{@link FrameLayout})包裹才能被監(jiān)聽(tīng)選中狀態(tài)。
- 在 xml 中使用
<com.source.yin.yinlayout.checkable.CommonCheckableGroup
android:id="@+id/common_checkable_group"
android:layout_height="wrap_content"
android:layout_width="match_parent"
app:multiple="true"
android:orientation="vertical">
<CheckedTextView
android:background="@drawable/background_selector"
android:layout_height="wrap_content"
android:layout_width="match_parent"
android:padding="10dp"
android:text="選項(xiàng)1"
android:textColor="@android:color/white" />
<com.source.yin.yinlayout.checkable.CheckableTag
android:background="@drawable/background_selector"
android:layout_height="wrap_content"
android:layout_marginTop="5dp"
android:layout_width="match_parent">
<TextView
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:padding="10dp"
android:text="選項(xiàng)2"
android:textColor="@android:color/white" />
</com.source.yin.yinlayout.checkable.CheckableTag>
</com.source.yin.yinlayout.checkable.CommonCheckableGroup>
將選項(xiàng)作為 CommonCheckableGroup 的子 view 即可實(shí)現(xiàn)所需效果。
xml 中設(shè)置 multiple 屬性為 ture 則表示可多選。
- 在代碼中使用
commonCheckableGroup.setLayoutAdapter(new BaseLayoutAdapter<String>(getApplicationContext(), stringList, R.layout.checkable_group_layout_item) {
@Override
public void dataBind(View itemView, int position, String data) {
TextView textView = (TextView) itemView.findViewById(R.id.tv_item);
textView.setText(data);
}
});
在代碼中通過(guò) adapter 的方式可以更靈活的設(shè)置多個(gè)選項(xiàng),BaseLayoutAdapter 構(gòu)造函數(shù)中的第3個(gè)參數(shù)中的 xml 即每個(gè)選項(xiàng)的布局文件,會(huì)在 dataBind() 回調(diào)中解析為 view 返回。使用者在此方法中將數(shù)據(jù)源與布局文件綁定顯示。
commonCheckableGroup.setCheckedListener(new CommonCheckableGroup.CheckedListener() {
@Override
public void onCheckChange(Checkable checkable) {
List<Checkable> checkedItemList = commonCheckableGroup.getCheckedItemList();
}
});
通過(guò) setCheckedListener() 設(shè)置選中事件監(jiān)聽(tīng)。通過(guò) getCheckedItemList() 得到當(dāng)前選中的對(duì)象列表。
如果你需要在 CheckableGroup 的子項(xiàng)被點(diǎn)擊,框架中的選中邏輯被觸發(fā)之前根據(jù)情況攔截此次事件,可以設(shè)置攔截器
commonCheckableGroup.setItemClickInterceptor(new CheckableGroupManager.ItemClickInterceptor() {
@Override
public boolean onInterceptorItemClick(Checkable checkable) {
if (...) {
//攔截
return true;
}
//不攔截
return false;
}
});
