Set the layout weight of a TextView programmatically
Asked Answered
G

12

223

I'm trying to dynamically create TableRow objects and add them to a TableLayout. The TableRow objects has 2 items, a TextView and a CheckBox. The TextView items need to have their layout weight set to 1 to push the CheckBox items to the far right.

I can't find documentation on how to programmatically set the layout weight of a TextView item.

Gonna answered 11/7, 2010 at 18:30 Comment(0)
J
365

You have to use TableLayout.LayoutParams with something like this:

TextView tv = new TextView(v.getContext());
tv.setLayoutParams(new TableLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT, 1f));

The last parameter is the weight.

Jerroldjerroll answered 11/7, 2010 at 19:33 Comment(5)
I didn't mention this before, so I'm sorry. But I tried this prior to asking my question. It makes the TextView disappear from the layout. But, on a positive note, I found that setting the stretch_columns property of the TableLayout to 0 causes the effect I'm looking for (TextView's on the left, CheckBoxes on the right). Thanks for the help.Gonna
If you are importing an XML layout and you are not creating your layout dynamically, you can grab it like this: TextView tv = (TextView) findViewById(R.id.your_textview_inside_the_linearlayout); tv.setLayoutParams(new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT, 0.1f));Warfield
To set the layout weight programmatically, TableRow.LayoutParams should be used instead of TableLayout.LayoutParams. See @Dorje's answer.Rogers
import android.widget.LinearLayout; import android.widget.TableLayout;Fractionate
table.setStretchAllColumns(true);Dapplegray
E
101

The answer is that you have to use TableRow.LayoutParams, not LinearLayout.LayoutParams or any other LayoutParams.

TextView tv = new TextView(v.getContext());
LayoutParams params = new TableRow.LayoutParams(0, LayoutParams.WRAP_CONTENT, 1f);
tv.setLayoutParams(params);

The different LayoutParams are not interchangeable and if you use the wrong one then nothing seems to happen. The text view's parent is a table row, hence:

http://developer.android.com/reference/android/widget/TableRow.LayoutParams.html

Eltonelucidate answered 31/7, 2012 at 16:6 Comment(5)
This answer helped me a lot...TableLayout did not worked for meDuckworth
Aw man, you saved me so much time. Where is it specified? I found nothing in documentation about you cannot interchange LayoutParamsMoreland
TableRow.LayoutParams did the job for me tooMascle
The key part of this answer is the 0Basuto
It will reduce my work time.Im searching for this for a long time.Very great solutionBlah
H
41

In the earlier answers weight is passed to the constructor of a new SomeLayoutType.LayoutParams object. Still in many cases it's more convenient to use existing objects - it helps to avoid dealing with parameters we are not interested in.

An example:

// Get our View (TextView or anything) object:
View v = findViewById(R.id.our_view); 

// Get params:
LinearLayout.LayoutParams loparams = (LinearLayout.LayoutParams) v.getLayoutParams();

// Set only target params:
loparams.height = 0;
loparams.weight = 1;
v.setLayoutParams(loparams);
Hepatitis answered 3/5, 2014 at 22:52 Comment(2)
loparams could be NULL so make sure you check that before calling setLayoutParams()Presentable
@AAgg, not in a practical situation. View wouldn't have inflated if it hadn't width and height set. But I agree - it's a good practice to check when there're doubts about null.Hepatitis
N
17
TextView txtview = new TextView(v.getContext());
LayoutParams params = new LinearLayout.LayoutParams(0, LayoutParams.WRAP_CONTENT, 1f);
txtview.setLayoutParams(params);

1f is denotes as weight=1; you can give 2f or 3f, views will move accoding to the space

Natividadnativism answered 29/2, 2016 at 7:15 Comment(0)
C
13

just set layout params in that layout like

create param variable

 android.widget.LinearLayout.LayoutParams params = new android.widget.LinearLayout.LayoutParams(
            LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT, 1f);

1f is weight variable

set your widget or layout like

 TextView text = (TextView) findViewById(R.id.text);
 text.setLayoutParams(params);
Churlish answered 4/5, 2013 at 9:8 Comment(2)
where do you get this information that 1f means the weight variable ? Can you provide a link please ?Jonellejones
@Jonellejones just check sources of LinearLayout.LayoutParams constructor. 3rd parameter is weight. Or documentationDoorkeeper
B
11
TextView text = new TextView(v.getContext());
text.setLayoutParams(new TableLayout.LayoutParams(LayoutParams.WRAP_CONTENT, 
                                                LayoutParams.WRAP_CONTENT, 1f));

(OR)

TextView tv = new TextView(v.getContext());
LayoutParams params = new TableRow.LayoutParams(0, LayoutParams.WRAP_CONTENT, 1f);
tv.setLayoutParams(params);

1f is refered as weight=1; according to your need you can give 2f or 3f, views will move accoding to the space. For making specified distance between views in Linear layout use weightsum for "LinearLayout".

LinearLayout ll_Outer= (LinearLayout ) view.findViewById(R.id.linearview);
LinearLayout llInner = new LinearLayout(this);
            LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.FillParent, LinearLayout.LayoutParams.WrapContent);
            llInner.Orientation = Orientation.Horizontal;
            llInner.WeightSum = 2;
            ll_Outer.AddView(llInner);
Bendix answered 8/12, 2014 at 11:52 Comment(0)
H
10

This should works to you

LinearLayout.LayoutParams param = new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT LayoutParams.MATCH_PARENT);

param.weight=1.0f;
Help answered 8/8, 2016 at 11:36 Comment(0)
T
7

You can also give weight separately like this ,

LayoutParams lp1 = new LayoutParams(LayoutParams.MATCH_PARENT,LayoutParams.MATCH_PARENT);

 lp1.weight=1;
Teheran answered 8/2, 2014 at 10:33 Comment(0)
P
6

This work for me, and I hope it will work for you also

Set the LayoutParams for the parent view first:

myTableLayout.setLayoutParams(new TableLayout.LayoutParams(TableLayout.LayoutParams.FILL_PARENT,
                TableLayout.LayoutParams.FILL_PARENT));

then set for the TextView (child):

 TableLayout.LayoutParams textViewParam = new TableLayout.LayoutParams
     (TableLayout.LayoutParams.WRAP_CONTENT,
     TableLayout.LayoutParams.WRAP_CONTENT,1f);
     //-- set components margins
     textViewParam.setMargins(5, 0, 5,0);
     myTextView.setLayoutParams(textViewParam); 
Pigeonwing answered 20/8, 2012 at 23:34 Comment(0)
A
2

After strugling for 4 hours. Finally, This code worked for me.

3 Columns are there in a row.

  TextView serialno = new TextView(UsersActivity.this);
  TextView userId = new TextView(UsersActivity.this);
  TextView name = new TextView(UsersActivity.this);

  serialno.setLayoutParams(new TableRow.LayoutParams(TableRow.LayoutParams.WRAP_CONTENT, TableRow.LayoutParams.WRAP_CONTENT, 1f));
  userId.setLayoutParams(new TableRow.LayoutParams(TableRow.LayoutParams.WRAP_CONTENT, TableRow.LayoutParams.WRAP_CONTENT, 1f));
  name.setLayoutParams(new TableRow.LayoutParams(TableRow.LayoutParams.WRAP_CONTENT, TableRow.LayoutParams.WRAP_CONTENT, 1f));
Aboriginal answered 20/4, 2019 at 15:18 Comment(0)
B
1

There is another way to do this. In case you need to set only one parameter, for example 'height':

TextView textView = (TextView)findViewById(R.id.text_view);
ViewGroup.LayoutParams params = textView.getLayoutParams();
params.height = ViewGroup.LayoutParams.WRAP_CONTENT;
textView.setLayoutParams(params);
Bonaventura answered 28/1, 2014 at 19:4 Comment(0)
Q
-1

I had a fair amount of difficulty with a solution something very similar to this: trying to have two buttons in a TableRow, with each being half the screen width. For whatever reason, the left button would always be about 70% of the width, and the right button 30%. Calling table_layout.setStretchAllColumns(true) had no effect, nor did setting the button's width to half the screen, nor setting their layout weight.

The solution I ended up with was nesting a LinearLayout in the TableRows, which did take into account the value of the buttons' width.

    TableLayout layout = new TableLayout(this);
    TableRow top_row = new TableRow(this);
    left_button = styleButton();
    right_button = styleButton();
    LinearLayout toprow_layout = new LinearLayout (this);
    toprow_layout.setOrientation(LinearLayout.HORIZONTAL);
    toprow_layout.addView (left_button);
    toprow_layout.addView(right_button);
    toprow.addView(top_layout);
    layout.addView(top_row)

    private Button styleButton() {
            Button btn = new Button (this);
            android.view.Display display = ((android.view.WindowManager)getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay();      
            btn.setWidth((int)(display.getWidth()/2));    // set width to half
            btn.setHeight(((int)display.getHeight()/6));  // set height to whatevs
            btn.setText("foo");
            return btn;
        }
Queer answered 2/9, 2011 at 20:3 Comment(1)
Just so you know for the future, the solution is to set the TableRow, Button1, and Button2 to all have layout_width=fill_parent, and after doing that, set the layout_weight=1 for both button1 and button2. All elements with fill_parent and a layout_weight=1 will be given an equal size upon inflation.Sherwood

© 2022 - 2024 — McMap. All rights reserved.