Kotlin合成扩展名,其中一些包含相同的布局 [英] Kotlin synthetic extension and several include same layout
问题描述
如果我的布局如下,如何使用kotlin合成扩展名进行查看:
How to access to view using kotlin synthetic extension if I have a layout like below:
file:two_days_view.xml
file: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
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>
如何访问dayName?我在找这样的东西:
How to access to dayName? I looked for some like this:
day1.dayName.text = "xxx"
day2.dayName.text = "sss"
我在Studio中看到我可以访问dayName
,但是dayName TextView引用了哪一个?
I see in Studio that I have access to dayName
but to which one of dayName TextView is reference to?
正常,如果我只有一个包含的布局,则效果很好.但是现在我多次包含相同的布局.
Normal if I have only one included layout it works fine. But now I have multiple times included same layout.
当然我总能做到:
day1.findViewById(R.id.dayName).text = "xxx"
但是我正在寻找不错的解决方案. :)
but I'm looking for nice solution. :)
推荐答案
作为一般的经验法则,您不应构建最终拥有多个具有相同id的视图的布局-正是由于这个原因.
As a general rule of thumb, you should not construct layouts that end up having multiple views with the same id - for this very reason.
但是,要解决您的问题: 而不是导入
But, to solve your problem: Instead of importing
kotlinx.android.synthetic.main.layout.day_row.*
您可以导入
kotlinx.android.synthetic.main.layout.day_row.view.*
(请注意末尾的其他.view
).
kotlinx.android.synthetic.main.layout.day_row.view.*
(Notice the additional .view
at the end).
这不会将视图导入为活动/片段"级别的属性,而是作为View
的扩展属性.这样,假设day1
和day2
包含所需的视图,就可以按照所需的方式进行操作:
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合成扩展名,其中一些包含相同的布局的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!