Android:为什么我不能将setText与findViewById放在同一行

Sta*_*hil 0 java android android-studio

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

TextView currentItem
currentItem = (TextView)findViewById(R.id.myText);
currentItem.setText("text");
Run Code Online (Sandbox Code Playgroud)

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

(TextView)findViewById(R.id.myText).setText("text");
Run Code Online (Sandbox Code Playgroud)

没什么大不了的,但我有一些代码需要大量的文本更新.如果我能在一条线上得到它,那就更清洁了.

Kak*_*rot 5

findViewById返回一个泛型' View',因此您必须TextView先将其强制转换为可以设置文本.在您的代码片段中,您尝试在"View"对象而不是"TextView"对象上调用setText.

试试这个 :

 ((TextView)findViewById(R.id.myText)).setText("text");
Run Code Online (Sandbox Code Playgroud)