[英]Kotlin change property value
我有通用 function,它应该将通用 object 绑定到视图。 我已经处理了从对象获取数据并从视图中获取字段名称。 但是现在我在分配这些数据时遇到了问题。
这个 function 迭代布局中的每个元素并获取 id,然后在 object function 上调用 get (布局元素的名称与对象中的名称相同)。 在 IF 语句中,我想将objectValue
(String) 分配给 TextView
class UniversalViewHolder<T : Any>(val bindingAny: ViewDataBinding) : RecyclerView.ViewHolder(bindingAny.root){
fun bind(elemAny: Any){
var binding = bindingAny.javaClass
binding.fields.forEach {
try {
val objectValue = readInstanceProperty<String>(elemAny,it.name)
Log.d(TAG,it.name+" "+objectValue)
if (it.type == TextView::class.java){
//here bind
}
}catch (ex: NoSuchElementException){
Log.e(TAG, "NO ELEMENT AT THIS FIELD "+ it.name)
}catch (ex:Exception){
Log.e(TAG,"CRASH AT THIS ELEM: " + it.name+"\n"+ex.stackTraceToString())
}
}
}
我在 bindingAny 中有属性 mText,然后在日期中,但是我如何才能访问其中的 mText 属性?
接下来我尝试通过binding.fields
更改此数据我可以接收包含类型但我没有找到任何更改文本的机会的字段 object
我也尝试访问方法 function setText(charSequence) 但我遇到了演员表问题
#EDIT 我的解决方案
fun bind(elemAny: Any,context: Context){
val binding = bindingAny.javaClass
binding.fields.forEach { field ->
try {
val objectValue = readInstanceProperty<String>(elemAny,field.name)
Log.d(TAG,field.name+" "+objectValue)
if (field.type == TextView::class.java){
arrayTextView.forEach {
if(context.resources.getResourceName(it.id).contains(field.name)){
it.text = objectValue
}
}
}
}catch (ex: NoSuchElementException){
Log.e(TAG, "NO ELEMENT AT THIS FIELD "+ field.name)
}catch (ex:Exception){
Log.e(TAG,"CRASH AT THIS ELEM: " + field.name+"\n"+ex.stackTraceToString())
}
}
}
private var arrayTextView : ArrayList<TextView> = ArrayList()
private fun searchLeaf(root: ViewGroup,context: Context){
while(true){
root.forEach {
if(it::class == MaterialTextView::class || it::class == TextView::class){
Log.d(TAG,context.resources.getResourceName(it.id))
arrayTextView.add(it as TextView)
// }else if ((it as ViewGroup).size == 0) {
}
else if((it as ViewGroup).size != 0){
try{
searchLeaf(it as ViewGroup,context)
}catch (ex:Exception){ }
}
}
break
}
}
如果有人在寻找答案。 我找到了如何处理这个问题的方法。 我只是将 binding.root 转换为 ViewGroup,
val x = (bindingAny.root as ViewGroup).children.first() as ViewGroup)
这样我就可以访问视图了,现在我可以像在二叉树中一样搜索所有 TextViews 但带有 n 叶
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.