【问题标题】:How to update textview declared in OnViewCreated from another function如何从另一个函数更新在 OnViewCreated 中声明的 textview
【发布时间】:2019-08-23 13:32:23
【问题描述】:

我正在尝试在 Kotlin 中更新我的片段的 TextView。在我的片段的onViewCreated 中声明TextView 时如何更新它?

onViewCreated 函数内部:

val txt = view.findViewById<View>(R.id.txt) as TextView

在另一个函数中:

fun update(){
    txt.text= "Hello"
}

【问题讨论】:

  • 能分享一下片段代码吗

标签: android kotlin android-context


【解决方案1】:

如果它在 onCreateView() 中声明,则无法访问它

相反,请在课堂级别尝试此操作。

class MyFragment : Fragment(){

   lateinit var txt: TextView

}

然后将你的 textView 分配给变量。

虽然我有 2 条建议给你:

  1. 不要在 onCreateView() 中实例化视图,尝试使用 onViewCreated() 实例化。

  2. 使用 kotlin 扩展或数据绑定来访问视图,这样可以省去很多麻烦,而且实际上更易于使用。

【讨论】:

  • 它在 onViewCreated() 里面
  • 这是最好的方法吗?谢谢,我想知道最好的方法。
  • 1. Google 建议使用 DataBinding。在您的片段或活动中没有视图引用,而是在 XML 中。只要通过观察实时数据来更改数据,视图就会动态更新。
  • 2.许多开发人员和我个人都喜欢 Kotlin 扩展,它们易于学习和使用。看看这篇文章(antonioleiva.com/kotlin-android-extensions
  • 谢谢,我想我会尝试数据绑定
【解决方案2】:

我使用 Manzur Alahi 的建议解决了这个问题。我没有使用findViewById来获取TextView,而是添加了直接访问TextView而不使用findViewById的插件。你可以在这里了解更多信息:https://antonioleiva.com/kotlin-android-extensions/

更新代码(无需在OnViewCreated 中声明任何内容):

fun update(){
Textview.txt="It works"
}

【讨论】:

    猜你喜欢
    • 2016-03-13
    • 1970-01-01
    • 1970-01-01
    • 2020-03-25
    • 2019-07-25
    • 2011-12-02
    • 1970-01-01
    • 2012-10-28
    • 1970-01-01
    相关资源
    最近更新 更多