How to access to view using kotlin synthetic extension if I have a layout like below:

文件:Two_day_view.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical">

    <include
        android:id="@+id/day1"
        layout="@layout/day_row"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />

    <include
        android:id="@+id/day2"
        layout="@layout/day_row"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />
</LinearLayout>

文件:day_row.xml

   <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical"       >

        <TextView
            android:id="@+id/dayName"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content" />

    </LinearLayout>

如何访问dayName?我找了一些这样的:

day1.dayName.text = "xxx"
day2.dayName.text = "sss"

我在Studio中看到我可以访问dayName,但dayName TextView指的是哪一个?

Normal if I have only one included layout it works fine. But now I have multiple times included same layout.

of course I can always do:

day1.findViewById(R.id.dayName).text = "xxx"

but I'm looking for nice solution. :)

推荐答案

作为一般的经验法则,您不应该构建最终具有相同id的多个视图的布局——正是出于这个原因.

但是,要解决你的问题: 而不是导入

kotlinx.android.synthetic.main.layout.day_row.*

你可以导入

kotlinx.android.synthetic.main.layout.day_row.view.*(请注意末尾额外的.view).

This will import the views not as properties on the Activity/Fragment level, but instead as extension properties for View. That way, you can do it the way you want, assuming that day1 and day2 contain the views you want:

day1.dayName.text = "xxx"
day2.dayName.text = "sss"

Kotlin相关问答推荐

在Kotlin Jetpack中重用下拉菜单

Kotlin中的增广赋值语句中的难以理解的错误

无法访问类kotlin.coroutines.CoroutineContext';.判断模块类路径中是否存在丢失或冲突的依赖项

mutableStateOf 在 Jetpack Compose 中不记住 API 的情况下保持重组后的值

Kotlin:查找集合中最常见的元素

Dagger 2 ContributesAndroidInjector 为模块提供活动

java - 如何将函数作为参数从java传递给kotlin方法?

Kotlin:泛型、反射以及类型 T 和 T:Any 之间的区别

Anko 中的水平线性布局

Kotlin 静态函数:伴生对象,@JvmStatic @JvmField

将 Completable 转换为 Single 的规范方法?

如何从定义它们的类外部调用扩展方法?

Kotlin通过映射委托属性,如果映射中不存在,则抛出NoTouchElementException

使用导航组件在不同的图形之间导航

Kotlin - computed var 属性的用处?

Kotlin数据类打包

导航架构组件 - 未生成 DestinationFragmentArgs

Kotlin flatMap - map

Kotlin内联属性的用例是什么?

使用 Moshi/Retrofit2 访问深度嵌套的 JSON 数组