简体   繁体   中英

Applying LayoutParams hides the View

In the code snippet below there's one commented line. When I uncomment that line, then the contents of LinearLayout are not displayed in a TableRow . Without setting the LayoutParams , the row displays both texts. I don't understand this behavior. I know that I can include complex views via xml files, but I'd rather understand what's wrong with this code:

    TableLayout tableLayout = (TableLayout) findViewById(R.id.table);

    TableRow tableRow = new TableRow(this );
    tableRow.setLayoutParams(new TableRow.LayoutParams(TableRow.LayoutParams.MATCH_PARENT, TableRow.LayoutParams.MATCH_PARENT));

    LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(TableRow.LayoutParams.MATCH_PARENT, TableRow.LayoutParams.MATCH_PARENT);

    LinearLayout linearLayout = new LinearLayout(this);
    linearLayout.setOrientation(LinearLayout.HORIZONTAL);
    // when I comment out this line, the row only shows the second text.
    // linearLayout.setLayoutParams(layoutParams);

    TextView textLabel = new TextView(this);
    textLabel.setText("inside linear layout");
    linearLayout.addView(textLabel);

    TextView message = new TextView(this);
    message.setText( "inside tablerow");

    tableRow.addView(linearLayout);
    tableRow.addView(message);

    tableLayout.addView(tableRow);

Assuming the question is something like "What's the issue of this? How to resolve this?" , here's my answer:

When you are setting LayoutParams to a View , those params would be used by the parent of this View to layout that View appropriately. So in your case what you have done is following:



    LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(...);
    linearLayout.setLayoutParams(layoutParams);
    tableRow.addView(linearLayout);

Now, the tableRow is confused, because it expects TableRow.LayoutParams in order to layout the view appropriately, but it suddenly finds out some other layout params. Whereas, had you not explicitly specified params (ie when linearLayout.setLayoutParams() is commented out), the default layout params would be generated .



    @Override
    protected LinearLayout.LayoutParams generateDefaultLayoutParams() {
        return new LayoutParams(); // this is TableRow.LayoutParams
    }

So, instead of creating LinearLayout.LayoutParams , create TableRow.LayoutParams :



    TableRow.LayoutParams layoutParams = new TableRow.LayoutParams(...);
    linearLayout.setLayoutParams(layoutParams);
    tableRow.addView(linearLayout);

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