![](/img/trans.png)
[英]Referencing views with the same id in different layouts with kotlin android extensions
[英]Kotlin Synthetic: Referencing views with the same ids in several layouts with dynamic inflating
我有兩個布局:data_a.xml和data_b.xml。 它們都用於顯示相同的數據,但布局不同。 兩種布局都有一個帶有id data_label
的TextView
。
我的自定義視圖DataView
允許擴展data_a.xml或data_b.xml以呈現我的數據,具體取決於具有layout
屬性的Styleable
。
DataView.kt:
class DataView(context: Context?, attrs: AttributeSet?) : ConstraintLayout(context, attrs) {
init {
var layoutResId = R.layout.data_a
if (attrs != null) {
val a = context?.theme?.obtainStyledAttributes(attrs, R.styleable.DataView, 0, 0)
try {
layoutResId = a!!.getResourceId(R.styleable.DataView_layout, layoutResId)
} finally {
a?.recycle()
}
}
View.inflate(context, layoutResId, this)
data_label.text = "Foobar" // this won't work if I choose data_b.xml as layout
}
}
attrs.xml:
<declare-styleable name="DataView">
<attr name="layout" format="reference"/>
</declare-styleable>
這就是我選擇使用哪種布局的方式:
<?xml version="1.0" encoding="utf-8"?>
...
<com.duh.DataView
android:id="@+id/data_view"
app:layout="@layout/data_a"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintEnd_toEndOf="parent"/>
有沒有辦法使用Kotlin Synthetic來做到這一點?
如果要使用Kotlin Synthetic導入具有相同ID的不同小部件,可以在導入中為它們添加別名:
import kotlinx.android.synthetic.main.data_a.view.data_label as labelA
import kotlinx.android.synthetic.main.data_b.view.data_label as labelB
然后在DataView
您可以將文本分配給非空的TextView
,具體取決於您膨脹的布局:
(labelA ?: labelB)?.text = "Foobar"
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.