简体   繁体   中英

Java: type casting question

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?

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");
((TextView) findViewById(R.id.lbSightName)).setText("Some Text");

再加上一组括号,应该可以:

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

只需添加括号。

当然

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

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

再加上一组括号就可以了

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