【问题标题】:Kotlin Synthetic: Referencing views with the same ids in several layouts with dynamic inflatingKotlin Synthetic:在具有动态膨胀的多个布局中引用具有相同 ID 的视图
【发布时间】:2018-10-03 18:46:04
【问题描述】:

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

我的自定义视图 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 来做到这一点?

【问题讨论】:

  • 如果您在两个布局上具有相同的 id,则在导入时只能使用其中一个。无论如何,Syntetic 的工作方式与 finviewbyid 相同。因此,如果 id 相同 - 它会找到必要的视图

标签: android kotlin kotlin-android-extensions


【解决方案1】:

如果您想使用 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"

【讨论】:

  • 我知道导入的别名,但目标布局必须在 DataView (import kotlinx...data_xxx...) 中命名这一事实是一个问题。如果稍后在项目中我想创建一个 data_c.xml 布局,我将不得不修改我不需要的 DataView 类。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-10-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多