Search code examples
androidlayouttextviewshort

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.


Solution

  • 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.