gpt4 book ai didi

java - 无法在与 findViewById(R.id.textView) 同一行中使用 setText() 方法

转载 作者:行者123 更新时间:2023-12-01 07:45:10 25 4
gpt4 key购买 nike

我无法在代码中使用 findViewById('R.id.textView').setText("message"),Android studio 显示此错误

Cannot resolve method 'setText(java.lang.String)

和这个问题Android: Why can I not setText in the same line as findViewById不一样在更新的 Android 版本中,我们不再需要对 findViewById() 方法进行转换,有关更多详细信息,请参阅此问题 No need to cast the result of findViewById?

最重要的是,如果我首先将 findViewById 的结果保存在变量中(无需手动将其转换为 TextView),则相同的代码可以工作,即

   TextView textview = findViewById(R.id.textview);
textview.setText("message");

上面的代码工作正常,如果 findViewById 返回 View 对象,那么它也应该不起作用,如果它返回 TextView 对象,那么一个线性代码 findViewById(' R.id.textView').setText("message") 应该也可以工作。

我知道如果我将它转换到 TextView 中,它就会起作用。但我的问题是,如果它已经返回 TextView 对象,为什么我需要强制转换?谢谢!

最佳答案

您需要将 textview 转换为 TextView:

((TextView) findViewById(R.id.textView)).setText("message")

关于java - 无法在与 findViewById(R.id.textView) 同一行中使用 setText() 方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54558034/

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