kotlin-解决在非Activity,Fragment,view中无法自动绑定id(kotlin-android-extensions)

本文介绍如何在Kotlin中使用内置资源绑定功能简化UI操作,尤其针对RecyclerView的ViewHolder模式,通过LayoutContainer实现更简洁的代码。文章还提供了详细的步骤,包括在build.gradle中配置kotlin-android-extensions插件,以及自定义ViewHolder类的实例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

首先Kotlin自带了资源绑定功能,类似与ButterKnife的@BindView

在资源文件中定义好id

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"                android:layout_width="match_parent"                                                  android:layout_height="match_parent"                                                 xmlns:app="http://schemas.android.com/apk/res-auto">

    <androidx.recyclerview.widget.RecyclerView
            android:id="@+id/recyclerview"
            android:layout_width="match_parent"
            android:layout_height="match_parent">

    </androidx.recyclerview.widget.RecyclerView>
    <Button
            android:text="add"
            app:layout_constraintBottom_toBottomOf="parent"
            android:id="@+id/add"
            android:layout_width="wrap_content" android:layout_height="wrap_content"/>
</androidx.constraintlayout.widget.ConstraintLayout>

activity中就可以直接根据id来对控件进行操作

class UserListActivity : AppCompatActivity() {
    private var adapter = UserAdapter()
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.user_list_activity)
        recyclerview.adapter = adapter
        recyclerview.addItemDecoration(
            androidx.recyclerview.widget.DividerItemDecoration(
                this,
                androidx.recyclerview.widget.DividerItemDecoration.VERTICAL
            )
        )
        add.setOnClickListener {
            startActivity(Intent(this,EditUserActivity::class.java ))
        }
    }
}

上面对教程肯定都一大堆了,就不废话了。

重点是像viewholder这种不属于activity,fragment,view的直接打id名称也是不行的。

直接引用 kotlinx.android.synthetic.xxx.xx也是不行的

对于这个问题其实官方早就给出答案了

就是要用到LayoutContainer,直接继承你又会发现找不到这个类。

因为还需要在app的build.gradle中添加

apply plugin: 'kotlin-android-extensions'
   androidExtensions {

        experimental = true
    }

 

然后就可以愉快的使用id了

下面是我自己的viewholder

class UserViewHolder : androidx.recyclerview.widget.RecyclerView.ViewHolder,LayoutContainer
{
    override val containerView: View?

    constructor(parent :View) : super( LayoutInflater.from(parent!!.context).inflate(
        R.layout.user_viewholder,
        parent as ViewGroup,
        false
    )) {

        containerView = itemView
    }

    fun setData(user: User) {
        vvh_name.text = user.name
        vvh_phone.text = user.phone

    }
}

参考链接 https://kotlinlang.org/docs/tutorials/android-plugin.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值