如何访问使用科特林合成分机,如果我有一个像下面的布局查看:
文件: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>
文件: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"
我在工作室,我有机会看到dayName
但到DAYNAME的TextView之一是参考?
正常的,如果我只有一个包含布局,它工作正常。但现在我有多次包括相同的布局。
当然,我总是可以这样做:
day1.findViewById(R.id.dayName).text = "xxx"
但是我正在寻找很好的解决方案。 :)
作为一般的经验法则,你不应该构建一个最终不得不用相同的ID多个视图布局 - 因为这个原因。
但是,要解决你的问题:代替进口
kotlinx.android.synthetic.main.layout.day_row.*
你可以导入
kotlinx.android.synthetic.main.layout.day_row.view.*
(注意在末尾附加.view
)。
这将不会导入意见的活动/片段级属性,而是作为View
扩展属性。这样一来,你可以做你想要的方式,假设day1
和day2
包含你想要的观点:
day1.dayName.text = "xxx"
day2.dayName.text = "sss"
我有同样的情况。这是我做了它的工作方式:
布局我的活动/片段:
<include
android:id="@+id/field1"
layout="@layout/merge_field"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<include
android:id="@+id/field2"
layout="@layout/merge_field"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
布局:merge_field.xml
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/mergeContainer"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<TextView
android:id="@+id/tv_title"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</FrameLayout>
科特林代码:
val tv_title = field1?.findViewById(R.id.tv_title)
tv_title.text = "This way it works"
注意<FrameLayout>
根视图。它只是为我工作这条路。
使用<merge>
标签没有奏效
“使用kotlin.synthetic用于布局块的危险” qazxsw POI
在这种情况下,使用方法:
https://link.medium.com/rMwau5VAZT