1

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");

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.

Soatl
  • 10,224
  • 28
  • 95
  • 153
  • Try sticking another pair of parentheses around `(TextView)findViewById(R.id.myText)` – awksp Jun 03 '14 at 21:55
  • Just remember, method invocations have higher precedence than casts. You'll need extra parentheses if you want to cast in the middle of a series of chained method calls. – awksp Jun 03 '14 at 21:57

3 Answers3

8

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.

Try this :

 ((TextView)findViewById(R.id.myText)).setText("text");
Kakarot
  • 4,252
  • 2
  • 16
  • 18
0

Try this please :

((TextView)findViewById(R.id.myText)).setText("text");
Farouk Touzi
  • 3,451
  • 2
  • 19
  • 25
0

findViewById returns a View, so you don't have setText from TextView yet. You have to cast first to TextView by putting parenthesis around findViewById and then call setText like this:

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

Also, this is a Java thing, not Android nor Android Studio thing.

AxiomaticNexus
  • 6,190
  • 3
  • 41
  • 61