gpt4 book ai didi

android - Kotlin 合成 : Referencing views with the same ids in several layouts with dynamic inflating

转载 作者:行者123 更新时间:2023-11-29 15:34:59 25 4
gpt4 key购买 nike

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

我的自定义 View DataView 允许膨胀 data_a.xml 或 data_b.xml 以呈现我的数据,具体取决于具有 layoutStyleable属性。

数据 View .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
}
}

属性.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"

关于android - Kotlin 合成 : Referencing views with the same ids in several layouts with dynamic inflating,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52633804/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com