如何在 values/ids.xml 中获取自定义 ID 的引用
How to get reference of custom ids in values/ids.xml
我在 recyclerView 适配器中使用 anko 来创建 viewholder 的视图。我已经成功完成了这项工作,但不知道如何使用 kotlin synthetic by view id 来引用它(我想在没有 findViewById 的情况下获取它)
value/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 创建的视图。
解决方法是使用 -
val txv1 = findViewById(R.id.txv1) as TextView
或
声明一个变量来保存在 anko 方法中创建的视图的引用。
代码如下 -
var txv1: TextView? = null
private fun getView(context: Context): View{
return with(context){
linearLayout {
txv1 = textView {
text = "TextView"
}
}
}
}
希望这对其他人有所帮助。谢谢
我在 recyclerView 适配器中使用 anko 来创建 viewholder 的视图。我已经成功完成了这项工作,但不知道如何使用 kotlin synthetic by view id 来引用它(我想在没有 findViewById 的情况下获取它)
value/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 创建的视图。
解决方法是使用 -
val txv1 = findViewById(R.id.txv1) as TextView
或
声明一个变量来保存在 anko 方法中创建的视图的引用。
代码如下 -
var txv1: TextView? = null
private fun getView(context: Context): View{
return with(context){
linearLayout {
txv1 = textView {
text = "TextView"
}
}
}
}
希望这对其他人有所帮助。谢谢