【问题标题】:Can't access view elements by LayoutInflater in Kotlin无法通过 Kotlin 中的 LayoutInflater 访问视图元素
【发布时间】:2021-09-04 17:16:58
【问题描述】:

我只是为我的 recyclerview 制作了一个适配器。像这样:

class CustomerAdapter(mCtx:Context,val customers:ArrayList<Customer>):RecyclerView.Adapter<CustomerAdapter.ViewHolder>(){

我有一个 xml 布局文件来扩充 recycleview 项目。

但问题出在onCreateViewHolder ...我无法访问膨胀的元素...

在我的 onCreateViewHolder 方法中编写的代码:

  override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): CustomerAdapter.ViewHolder {
        val v = LayoutInflater.from(parent.getContext()).inflate(R.layout.lo_customers, parent, false);
        var txt = v.id

    }

我无法通过 id 访问视图元素。

【问题讨论】:

  • 你在kotlin文件中导入了合成布局吗?
  • 是的!我忘了加import kotlinx.android.synthetic.main.lo_customers.view.*,谢谢提醒
  • 合成已弃用,考虑迁移到视图绑定

标签: android android-studio kotlin android-recyclerview


【解决方案1】:

即使捕获View,也无法直接访问View 中的孩子。为了得到孩子的,你需要使用 findViewById(R.id.my_textView_id)View 对象上。

因此将您的v.txt 替换为v.findViewById(R.id.my_text_view_id)

【讨论】:

  • 这是 kotlin 不是 Java
【解决方案2】:

这是完全错误的做法。 onCreateViewHolder 函数名称本身表示它仅用于膨胀视图而不做其他任何事情。它应该只用于创建 ViewHolder 。即使您从那里扩充您的视图并分配视图,它也将在未来崩溃。您必须在那里膨胀视图并将父视图传递给另一个应该扩展 RecyclerView.ViewHolder() 的类。

所以按照以下方式进行:

override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): CustomerAdapter.ViewHolder {
        val v = LayoutInflater.from(parent.getContext()).inflate(R.layout.lo_customers, parent, false);
   
    }

创建一个扩展 RecyclerView.ViewHolder 的 ViewHolder 类:

 class CustomViewHolder(val view: View) :
        RecyclerView.ViewHolder(view) {
        fun bind(model  : Model) {

         //Now here you can access all the components present in your layout in the following way and do the stuff you want with them: 
           val text = view.findViewById(R.id.viewid)
        }
    }

【讨论】:

    【解决方案3】:

    问题解决了。

    在 gradle 应用中

    plugins {
       id 'kotlin-android-extensions'
    }
    

    apply plugin: 'kotlin-android-extensions'
    

    然后你的 Activity 导入这个

    import kotlinx.android.synthetic.main.activity_main.*
    

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-11-08
    • 1970-01-01
    • 2023-04-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-10-14
    • 1970-01-01
    相关资源
    最近更新 更多