Android RecycleView单选实现。

在这里插入图片描述

适配器

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>

好记性不如烂笔头!

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值