2017-02-24 22 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