sensorario
sensorario

Reputation: 21698

How to set android:layout_width="match_parent" from code?

I've different layout. Some created by xml. Some others dynamically via code. When I am on xml I can set width or height with "wrap_content" value. How to get the same result dynamically? This is the snippet of my dynamic TextView. I need to remove "final int width = 440;" and get same value of "wrap_content". How?

final int width = 440;
final int height = textViewHeight;
final int top = getNewTop(height);

FrameLayout.LayoutParams layoutParams;
layoutParams = getLayoutParams(width, height, top);

TextView textView;
textView = new TextView(_registerNewMealActivity);
textView.setText(text);
textView.setLayoutParams(layoutParams);

_frameLayout.addView(textView);

Upvotes: 13

Views: 27226

Answers (6)

In general, you should use

textView.setLayoutParams(new FrameLayout.LayoutParams(width, height));

where width and height are each one of the following:

  • A number, to make the view exactly that many pixels wide or tall (to specify a number in dp instead of pixels, see here)
  • FrameLayout.LayoutParams.WRAP_CONTENT
  • FrameLayout.LayoutParams.MATCH_PARENT

Also, if you're using LinearLayout, you should use LinearLayout.LayoutParams instead, and the same for RelativeLayout.

For example, if you want textView to have the same behavior as if it was declared as <TextView android:layout_width="wrap_content" android:layout_height="match_parent"/>, you would do

textView.setLayoutParams(new FrameLayout.LayoutParams(FrameLayout.LayoutParams.WRAP_CONTENT, FrameLayout.LayoutParams.MATCH_PARENT));

Upvotes: 2

Muthuraja
Muthuraja

Reputation: 551

try this>>>

layoutParams.getLayoutParams().width = 20;

Upvotes: -3

GrIsHu
GrIsHu

Reputation: 23638

Try out as below:

FrameLayout.LayoutParams layoutParams;
layoutParams = getLayoutParams(LayoutParams.WRAP_CONTENT, height, top);

  TextView textView;
textView = new TextView(_registerNewMealActivity);
textView.setText(text);
textView.setLayoutParams(layoutParams);

Upvotes: 8

Ravneet Singh
Ravneet Singh

Reputation: 213

You can do something like this.

    RelativeLayout.LayoutParams flparams = new RelativeLayout.LayoutParams(LayoutParams.MATCH_PARENT,(int)height);
            youlayoutname.setLayoutParams(flparams);

Upvotes: 0

SilentKiller
SilentKiller

Reputation: 6942

You can use :

textView.setLayoutParams(new FrameLayout.LayoutParams(LayoutParams.WRAP_CONTENT, height));

Upvotes: 9

Apoorv
Apoorv

Reputation: 13520

You can use FrameLayout.LayoutParams.WRAP_CONTENT for width

Upvotes: 2

Related Questions