简体   繁体   中英

programatically define a TextView within a LinearLayout in one line

I know this is possible to do in multiple lines like this:

    LinearLayout table=new LinearLayout(this);
    TextView titleText = new TextView(this);
    titleText.setText("Med Info");
    LinearLayout table=new LinearLayout(this);
    table.addView(titleText);

Is there a way to do this in one line without using XML? I already tried this:

LinearLayout table=new LinearLayout(this);
    table.addView(new TextView(this).setText("Med Info"));

which did not work (Wrong return value). I checked the TextView constructor, but nothing seemed to fit my goal. I am merely trying to shorten already existing code, not a serious project.

No, this is not possible without creating a wrapper function, since both .addView() and .setText() return void .

You should have no need to do this anyway. Readability is far more important than compressing lines of code.

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