2017-02-24 48 views
3

如何访问使用科特林合成的扩展,如果我有一个布局像下面查看:科特林合成的延伸和几个包括相同的布局

文件: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" 

,但我正在寻找很好的解决方案。 :)

回答

9

作为一般的经验法则,您不应该使用相同的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" 
+1

THX它wokrs。 顺便说一句:你能解释为什么不应该以这种方式构建布局?如果我有固定相同的7行?为什么我应该使用名称day(1..7)名称等来创建一个巨大的xml。任何差异的方式来避免巨大的XML? – LunaVulpo

+0

@LunaVulpo这更像是来自我身边的“免责声明”。我认为在你的情况下,对于固定的一组相同的布局,它可能是有保证的,但在很多情况下,其他解决方案可能更适合,比如使布局成为片段或自定义视图。我意识到这在技术上仍然将相同ID的视图放置在相同的结果布局中,但这样它们在代码中完全分离。 – Robin

+0

@ Hikaaru755好的。谢谢 :) – LunaVulpo