Android:为什么我不能将setText与findViewById放在同一行 [英] Android: Why can I not setText in the same line as findViewById

查看:70
本文介绍了Android:为什么我不能将setText与findViewById放在同一行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不确定这是Android问题还是AndroidStudio问题.为什么这样有效:

I am not sure if this is an Android issue or a AndroidStudio issue. Why is this valid:

TextView currentItem
currentItem = (TextView)findViewById(R.id.myText);
currentItem.setText("text");

但这不是(无法解析方法setText(Java.Lang.String))

But this is not (cannot resolve method setText(Java.Lang.String))

(TextView)findViewById(R.id.myText).setText("text");

没什么大不了的,但是我有一些需要大量文本更新的代码.如果我能在一行中得到它,那就干净得多.

Not a big deal, but I have some code that requires a lot of text updates. It would be much cleaner if I could get this in one line.

推荐答案

findViewById 返回通用的" View ",因此您必须将其转换为 TextView之前,您可以设置文本.在您的代码段中,您试图在'View'对象而不是'TextView'对象上调用setText.

findViewById returns a generic 'View', hence you have to cast it to TextView before you can set the text. In your piece of code you are trying to invoke setText on the 'View' object rather than the 'TextView' object.

尝试一下:

 ((TextView)findViewById(R.id.myText)).setText("text");

这篇关于Android:为什么我不能将setText与findViewById放在同一行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆