适配器
class HomeRadioAdapter() : BaseQuickAdapter<Category, BaseViewHolder>(R.layout.item_radiobtn, null) {
private var defItem = -1 //默认值
//获取点击的位置
fun setDefSelect(position: Int) {
defItem = position
//更新
notifyDataSetChanged()
}
override fun convert(helper: BaseViewHolder?, item: Category?) {
var textView = helper?.getView<TextView>(R.id.recycle_text)
textView!!.setText(item!!.category_name)
if (defItem!=-1){
//是当前的
if (defItem==helper!!.layoutPosition){
textView.setBackground(mContext.getResources().getDrawable(R.drawable.item_shape_radio_c));
textView.setTextColor(Color.parseColor("#FFFFFF"));
}else{
//不是当前
textView.setBackground(mContext.getResources().getDrawable(R.drawable.item_shape_radio_n));
textView.setTextColor(Color.parseColor("#000000"));
}
}
}
//默认第一个选中
adapter.setDefSelect(0)
adapter.setOnItemClickListener { aadapter, view, position ->
//点击后选中
adapter.setDefSelect(position)
}
xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal"
>
<!--单选-->
<TextView
android:id="@+id/recycle_text"
android:background="@drawable/item_shape_radio_n"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:button="@null"
android:gravity="center" />
</LinearLayout>
选中未选中的效果
R.drawable.item_shape_radio_n
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
<solid android:color="#fff"/>
<corners android:radius="30dp"/>
<padding
android:left="20dp"
android:right="20dp"
android:top="10dp"
android:bottom="10dp"
/>
<stroke
android:width="1dp"
android:color="#807F7F"
/>
</shape>
R.drawable.item_shape_radio_c
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
<solid android:color="@color/colorAccent"/>
<corners android:radius="30dp"/>
<padding
android:left="20dp"
android:right="20dp"
android:top="10dp"
android:bottom="10dp"
/>
</shape>
好记性不如烂笔头!