Kotlin合成扩展和几个包括相同的布局

Lun*_*lpo 13 android kotlin kotlin-android-extensions

如果我有如下布局,如何使用kotlin合成扩展访问视图:

文件:two_days_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>
Run Code Online (Sandbox Code Playgroud)

file: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>
Run Code Online (Sandbox Code Playgroud)

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

day1.dayName.text = "xxx"
day2.dayName.text = "sss"
Run Code Online (Sandbox Code Playgroud)

我在Studio中看到我有权访问dayName但是dayName TextView引用了哪一个?

正常,如果我只有一个包含的布局,它工作正常.但现在我有多次包含相同的布局.

我当然可以这样做:

day1.findViewById(R.id.dayName).text = "xxx"
Run Code Online (Sandbox Code Playgroud)

但我正在寻找好的解决方案.:)

Rob*_*bin 38

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

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

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

你可以导入

kotlinx.android.synthetic.main.layout.day_row.view.*(注意最后的附加内容.view).

这将导入视图而不是作为活动/片段级别的属性,而是作为扩展属性导入View.这样,您可以按照自己的方式进行,假设day1day2包含您想要的视图:

day1.dayName.text = "xxx"
day2.dayName.text = "sss"
Run Code Online (Sandbox Code Playgroud)

  • 是它的吵闹.顺便说一句:你能解释为什么不应该以这种方式构建布局吗?如果我修复了相同的7行?为什么我要创建一个名称为day(1..7)name的巨大xml,依此类推.任何差异化的方式来避免巨大的xml? (2认同)