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

Viewed 23562

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

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