[android] Set the layout weight of a TextView programmatically

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.

This question is related to android layout textview android-layout-weight

The answer is


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;
        }

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));

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);

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);

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.


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);

You can also give weight separately like this ,

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

 lp1.weight=1;

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


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


This should works to you

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

param.weight=1.0f;

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);

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); 

Examples related to android

Under what circumstances can I call findViewById with an Options Menu / Action Bar item? How to implement a simple scenario the OO way My eclipse won't open, i download the bundle pack it keeps saying error log getting " (1) no such column: _id10 " error java doesn't run if structure inside of onclick listener Cannot retrieve string(s) from preferences (settings) strange error in my Animation Drawable how to put image in a bundle and pass it to another activity FragmentActivity to Fragment A failure occurred while executing com.android.build.gradle.internal.tasks

Examples related to layout

This view is not constrained What's the difference between align-content and align-items? CSS Flex Box Layout: full-width row and columns Fill remaining vertical space with CSS using display:flex What is setContentView(R.layout.main)? How to change line color in EditText Scrolling a flexbox with overflowing content UICollectionView - Horizontal scroll, horizontal layout? How to style a div to be a responsive square? 100% width Twitter Bootstrap 3 template

Examples related to textview

Kotlin: How to get and set a text to TextView in Android using Kotlin? How to set a ripple effect on textview or imageview on Android? The specified child already has a parent. You must call removeView() on the child's parent first (Android) Android: Creating a Circular TextView? android on Text Change Listener Android - Set text to TextView Placing a textview on top of imageview in android Rounded corner for textview in android Different font size of strings in the same TextView Auto-fit TextView for Android

Examples related to android-layout-weight

What is android:weightSum in android, and how does it work? android:layout_height 50% of the screen size How to set layout_weight attribute dynamically from code? Set the layout weight of a TextView programmatically Linear Layout and weight in Android