Kotlin Synthetic:在具有动态膨胀的多个布局中引用具有相同 ID 的视图

rio*_*iot 2 android kotlin kotlin-android-extensions

我有两个布局:data_a.xml 和 data_b.xml。它们都用于显示相同的数据,但布局不同。两种布局都有一个TextViewid data_label

我的自定义视图DataView允许膨胀 data_a.xml 或 data_b.xml 以呈现我的数据,具体取决于是否Styleable具有layout属性。

数据视图.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
    }
}
Run Code Online (Sandbox Code Playgroud)

attrs.xml:

<declare-styleable name="DataView">
    <attr name="layout" format="reference"/>
</declare-styleable>
Run Code Online (Sandbox Code Playgroud)

这就是我选择要使用的布局的方式:

<?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"/>
Run Code Online (Sandbox Code Playgroud)

有没有办法使用 Kotlin Synthetic 来做到这一点?

Tij*_*jee 6

If you want to import different widgets with the same ID with Kotlin Synthetic, you can alias them in your imports:

import kotlinx.android.synthetic.main.data_a.view.data_label as labelA
import kotlinx.android.synthetic.main.data_b.view.data_label as labelB
Run Code Online (Sandbox Code Playgroud)

Then in your DataView you can assign your text to the TextView which is not null, depending on the layout you inflated:

(labelA ?: labelB)?.text = "Foobar"
Run Code Online (Sandbox Code Playgroud)