如何使用Kotlins视图绑定访问另一个类内部的视图

时间:2019-04-14 07:44:29

标签: android kotlin android-recyclerview android-view kotlin-extension

我目前正在关注有关RecyclerView的教程,该教程是用Java“编写”的。 现在,我主要尝试着本教程并在Kotlin中进行编码。 我现在想从单独创建的类“ RecyclerViewAdapter”中,从layout_listitem.xml(基本上只描述recyclerview中的单个元素的结构)访问视图。

这实际上是应该与单独的xml文件一起使用还是真正的问题?

PS:我也尝试使用 “导入kotlinx.android.synthetic.main.layout_listitem。*”,但这似乎也不起作用。

RecyclerViewAdapter

package com.gmail.mynamepackage.recyclerviewdemo
import android.content.Context
import android.support.v7.widget.RecyclerView
import android.view.View
import android.view.ViewGroup

class RecyclerViewAdapter : RecyclerView.Adapter<RecyclerViewAdapter.ViewHolder> {

   //In this complete class i am not able to access the views directly
}

layout_listitem.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:padding="15dp"
                android:id="@+id/parentLayout">

    <de.hdodenhof.circleimageview.CircleImageView
            android:layout_width="80dp"
            android:layout_height="80dp"
            android:id="@+id/image"
            android:src="@mipmap/ic_launcher"/>
    <TextView android:layout_width="wrap_content"
              android:layout_height="wrap_content"
              android:text="Canada"
want to acc:  android:id="@+id/image_name"
              android:layout_toRightOf="@+id/image"
              android:textColor="#000"
              android:layout_centerVertical="true"
              android:layout_marginLeft="58dp"
              android:textSize="17sp"
    />
</RelativeLayout>

2 个答案:

答案 0 :(得分:0)

尝试import kotlinx.android.synthetic.main.layout_listitem.view.*

如果要在View上调用综合属性,则还应该导入 view.*

答案 1 :(得分:0)

所以基本上发生了什么,我调查了RecyclerView类,偶然发现了一个itemItemView字段,该字段基本上使您可以访问RecyclerView节点的视图。