0

Is there any way to do this in a single line:

    TextView tv = (TextView) findViewById(R.id.lbSightName);
    tv.setText("Some Text");

I would like to do away declaring the intermediary tv, like so:

(TextView) findViewById(R.id.lbSightName).setText("Some Text");

Not possible?

Hein du Plessis
  • 3,305
  • 6
  • 34
  • 51

6 Answers6

5

You can, but it isn't best practice

((TextView) findViewById(R.id.lbSightName)).setText("Some Text");
TextView.class.cast(findViewById(R.id.lbSightName).setText("Some Text");
Stan Kurilin
  • 15,614
  • 21
  • 81
  • 132
  • Thanks, why not best practice? – Hein du Plessis Mar 21 '11 at 17:09
  • @Hein - You should prefer polymorphism / visitor pattern to instanceof/casting for dispatching in Java. – Stan Kurilin Mar 21 '11 at 17:18
  • @Hein - see my answer at http://stackoverflow.com/questions/4326017/implementing-generic-interface-in-java/4326117#4326117 , wiki (http://en.wikipedia.org/wiki/Visitor_pattern) , and GoF (http://en.wikipedia.org/wiki/Design_Patterns_%28book%29) for details – Stan Kurilin Mar 21 '11 at 17:33
4
((TextView) findViewById(R.id.lbSightName)).setText("Some Text");
Jan Zyka
  • 17,460
  • 16
  • 70
  • 118
2

With one more set of parenthesis it should be possible:

((TextView)findViewById(R.id.lbSightName)).setText("Some Text");
justkt
  • 14,610
  • 8
  • 42
  • 62
2
((TextView) findViewById(R.id.lbSightName)).setText("Some Text");

Just add braces.

paztulio
  • 351
  • 1
  • 3
2

Sure

((TextView) findViewById(R.id.lbSightName)).setText("Some Text");
user229044
  • 232,980
  • 40
  • 330
  • 338
willcodejavaforfood
  • 43,223
  • 17
  • 81
  • 111
1

((TextView)findViewById(R.id.lbSightName)).setText("Some thingy");

Adding one more set of parenthesis does the trick

Deepak
  • 2,094
  • 8
  • 35
  • 48