简体   繁体   中英

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). 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)

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. So you can't initialize a TextView variable with the result of setText() like you were trying to do.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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