简体   繁体   English

为TextView链接findViewById()时,未定义方法setText()

[英]Undefined method setText() when chaining findViewById() for TextView

I was wondering if anyone could tell me why: 我想知道是否有人可以告诉我原因:

TextView textblock = (TextView) findViewById(R.id.label).setText("Google is your friend.", TextView.BufferType.EDITABLE);

I get an undefined method error (setText is undefined for this type of view). 我收到未定义的方法错误(此类型的视图的setText未定义)。 However works when I do not chain eg: 但是当我不链接时有效,例如:

TextView textblock = (TextView)findViewById(R.id.label);
textblock.setText("Google is your friend.", TextView.BufferType.EDITABLE);

(I know this is a very basic question, however I am new to Java and could not find anything in my searches) (我知道这是一个非常基本的问题,但是我是Java新手,无法在搜索中找到任何内容)

You need to call the method on the casted result, thanks to additional parentheses: 由于附加括号,您需要在转换结果上调用该方法:

((TextView) findViewById(R.id.label)).setText("Google is your friend.", TextView.BufferType.EDITABLE);

That said, introducing a variable makes the code more readable. 也就是说,引入变量会使代码更具可读性。 I would do that instead. 我会这样做。

Also note that setText() returns void, and not the TextView. 还要注意, setText()返回void,而不是TextView。 So you can't initialize a TextView variable with the result of setText() like you were trying to do. 因此,您无法像尝试那样使用setText()的结果初始化TextView变量。

setText()的类型为void因此它不返回任何内容,这意味着您不能存储在变量中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM