philip
philip

Reputation: 1302

View not showing in layout when layoutparams is set programatically

Every time I set the layout param of TextView to wrap content or fill parent it's not showing in the view, but when I set it to pixels it's working why is that?

Here is the relevant code:

items = (LinearLayout) findViewById(R.id.llmain);
        tb = new TableLayout(MainActivity.this);

        tb.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
        tb.setGravity(Gravity.CENTER);


            TableRow tr = new TableRow(MainActivity.this);
            ImageButton ima = new ImageButton(MainActivity.this);
            ImageButton imr = new ImageButton(MainActivity.this);
            TextView tvin = new TextView(this);

            TableRow.LayoutParams trp = new TableRow.LayoutParams();
            trp.setMargins(0, 0, 0, 10);
            tr.setLayoutParams(trp);
            tr.setGravity(Gravity.CENTER);

            ima.setBackgroundColor(Color.TRANSPARENT);
            ima.setImageResource(R.drawable.add);

            imr.setBackgroundColor(Color.TRANSPARENT);
            imr.setImageResource(R.drawable.remove);

            tvin.setWidth(100);
            tvin.setHeight(45);
            tvin.setGravity(Gravity.CENTER);
            tvin.setText(sil[i]);
            tvin.setBackgroundColor(Color.rgb(200, 0, 255));

            tr.addView(ima);
            tr.addView(tvin);
            tr.addView(imr);

            tb.addView(tr);

        items.addView(tb);

I tried using this

tvin.setLayoutParams(new LayoutParams(
            LayoutParams.FILL_PARENT,
            LayoutParams.WRAP_CONTENT));

and this

tvin.setWidth(LayoutParams.FILL_PARENT);
tvin.setHeight(LayoutParams.FILL_PARENT);

but none of these work.

Upvotes: 0

Views: 1143

Answers (3)

Michiel Bijlsma
Michiel Bijlsma

Reputation: 583

Try to use the LinearLayout.LayoutParams

    TextView tvin = new TextView(this);
    LinearLayout.LayoutParams llp = new LinearLayout.LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT);
    tvin.setLayoutParams(llp);

Upvotes: 1

mainu
mainu

Reputation: 448

In this Line u have to use height and width .. TableRow.LayoutParams trp = new TableRow.LayoutParams(); Like this

TableRow row = new TableRow(context);
row.setLayoutParams(new android.widget.TableRow.LayoutParams(android.widget.TableRow.LayoutParams.FILL_PARENT,
                android.widget.TableRow.LayoutParams.WRAP_CONTENT));

Upvotes: 1

Mark
Mark

Reputation: 5566

Try:

tvin.setLayoutParams(new TableRow.LayoutParams(
            LayoutParams.MATCH_PARENT,
            LayoutParams.WRAP_CONTENT));

and remove the tvin.setWidth and height.

You should always set the layout params of view's parent, TableRow in this case. MATCH_PARENT makes no difference but it's a new name and you should be using it instead of FILL_PARENT.

Upvotes: 4

Related Questions