gpt4 book ai didi

android - 如何在 values/ids.xml 中获取自定义 ID 的引用

转载 作者:搜寻专家 更新时间:2023-11-01 09:34:15 26 4
gpt4 key购买 nike

我在 recyclerView 适配器中使用 anko 来创建 viewholder 的 View 。我已经成功完成了这项工作,但不知道如何使用 kotlin synthetic 通过 View id 来引用它(我想在没有 findViewById 的情况下获取它)

值/ids.xml

<resources>
<item name="txv1" type="id"/>
<item name="txv2" type="id"/>

我的 Anko getView 代码:

private fun getView(context: Context): View{
return with(context){
linearLayout {
lparams(width = matchParent, height = wrapContent)
padding = dip(10)
orientation = android.widget.LinearLayout.HORIZONTAL

//Task Number
textView {
id = R.id.txv1
text = "TextView 22"
textSize = 16f
typeface = Typeface.MONOSPACE
padding =dip(5)
}.lparams(){
weight = 1f
}

//Task Name
textView {
id = R.id.txv2
text= "TextView 33"
textSize = 16f
typeface = android.graphics.Typeface.DEFAULT_BOLD
padding =dip(5)
}
}
}
}

我正在从 ids.xml 分配自定义 ID,但是如何在没有 findViewById 的情况下获取它

谢谢

最佳答案

经过大量研究后,我得出结论,目前无法通过 id 直接引用 anko 创建的 View 。
解决方法是使用 -

val txv1 = findViewById(R.id.txv1) as TextView

或者
声明一个变量来保存在 anko 方法中创建的 View 的引用。
代码如下 -

    var txv1: TextView? = null

private fun getView(context: Context): View{
return with(context){
linearLayout {
txv1 = textView {
text = "TextView"
}
}
}
}

希望这对其他人有帮助。谢谢

关于android - 如何在 values/ids.xml 中获取自定义 ID 的引用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44695573/

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