【发布时间】: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