0

I can't able to use findViewById('R.id.textView').setText("message") in my code, Android studio shows this error

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

It is not the same as this question Android: Why can I not setText in the same line as findViewById as in updated android versions we no longer need to do casting for findViewById() method, for more details see this question No need to cast the result of findViewById?

Above all, the same code works if I save the result of findViewById in a variable first(Without casting it to TextView manually) i.e

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

Above code works fine, if findViewById returns View object then it should also not work, and if it returns TextView object then one linear code findViewById('R.id.textView').setText("message") should work as well.

I know if I cast it in TextView then it will work. but my question is why do I need to cast if it already returns TextView object? thanks!

nikhil123
  • 48
  • 1
  • 10

4 Answers4

3

You need to cast the view into a TextView

((TextView)findViewById(R.id.textView)).setText("message")
Tiago Ornelas
  • 1,109
  • 8
  • 21
3

You need to cast textview to TextView:

((TextView) findViewById(R.id.textView)).setText("message")
forpas
  • 160,666
  • 10
  • 38
  • 76
  • thanks, but why do i need to cast if it already returns `TextView` object? – nikhil123 Feb 06 '19 at 16:22
  • The compiler does not know that the view will be a TextView. – forpas Feb 06 '19 at 16:23
  • This is why if you first do this: `TextView textview = findViewById(R.id.textview);` the compiler will have no problem to do next: `textview.setText("message");` – forpas Feb 06 '19 at 16:25
1

The reason your example works is because static type assignment (through the variable declaration and assignment) promises that the object will be a TextView, which indeed does have the setText() method, or a runtime exception will occur.

setText() isn't defined in the View class, so directly calling it on a method returning a View object results in an exception because the compiler only knows the method doesn't exist in the returned View object. Parents aren't inferred as a child instance. You as the developer check or explicitly state it (casting or variable declaration and assignment)

An explicit cast on findViewById() to TextView adds the "promise" that the object will be a class with the method defined, so it'll compile.

0

Is this in a Fragment? If so, make sure you are using the view passed within onViewCreated(view: View, savedInstanceState: Bundle?). Something like this:

view.findViewById<TextView>(R.id.textview).setText("message")

Granted my answer is written in Kotlin, but you should be able to transpose to Java with ease. Let me know if this helps.