Kotlin中如何在函数内部声明TextView?findViewById失效问题求解
解决函数内声明/获取TextView的问题
情况1:从现有布局中查找已存在的TextView
你当前代码里的findViewById(R.id.idt)写法错误,R.id.idt是引用资源文件中定义的固定ID,而你的参数idt是传入的动态ID值,应该直接用findViewById(idt)来查找。修改后的代码如下:
fun addingNewText(idt: Int): TextView { val newtext = findViewById<TextView>(idt) // 也可以用 findViewById(idt) as TextView val parameter = LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT) newtext.layoutParams = parameter newtext.tag = idt.toString() return newtext }
注意:这种写法的前提是布局中已经存在ID为idt的TextView,否则findViewById会返回null,调用方法时可能崩溃,建议添加空判断优化:
fun addingNewText(idt: Int): TextView? { val newtext = findViewById<TextView>(idt) ?: return null val parameter = LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT) newtext.layoutParams = parameter newtext.tag = idt.toString() return newtext }
情况2:创建一个全新的TextView(符合函数名addingNewText的语义)
如果你的需求是新建一个TextView而不是查找已有控件,那不需要用findViewById,直接实例化TextView即可,代码如下:
fun addingNewText(idt: Int, context: Context): TextView { val newtext = TextView(context) // 若需要后续通过ID查找这个新控件,可设置ID newtext.id = idt val parameter = LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT) newtext.layoutParams = parameter newtext.tag = idt.toString() // 可按需添加文本、样式等属性 // newtext.text = "新文本内容" return newtext }
这种方式需要传入Context(创建View必须依赖上下文),之后你可以通过布局容器的addView(newtext)方法,把这个新建的TextView添加到界面中。
内容的提问来源于stack exchange,提问作者user19887284
相关产品推荐
相关产品推荐

