1

I have a simple button view, and set it as content view. Is it possible to resize this view programmaticly to "wrap_content"?

Button button = new Button(getContext());
button.setText("Some text");
setContentView(button);

3 Answers3

1

Set your attributes using the following code:

Button button = new Button(getContext());

LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT,
        LayoutParams.WRAP_CONTENT);
button.setLayoutParams(params);

button.setText("Some text");
setContentView(button);
Bhavesh Rangani
  • 1,490
  • 12
  • 23
0

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

Button button = new Button(getContext());

LinearLayout.LayoutParams params = new   LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT,
        LayoutParams.WRAP_CONTENT);
button.setLayoutParams(params);
params.weight = 1.0f;
button.setText("Some text");
setContentView(button);
Ahmad Aghazadeh
  • 16,571
  • 12
  • 101
  • 98
0

You can not set LayoutParams for a view without parent.

mr.icetea
  • 2,607
  • 3
  • 24
  • 42
  • Is thats mean I don't have any way to change view sizes witout wrapping this view in layout? – Vitali Zaharenko Mar 07 '16 at 12:35
  • Yes, without layout your button can't display. – mr.icetea Mar 07 '16 at 12:36
  • My button can display, and it have with and height equal to screen sizes, but seems android don't create some layout implicitly, because getParrent() or getLayoutParams() returns null – Vitali Zaharenko Mar 07 '16 at 12:44
  • @VitaliZaharenko In fact your button in this case will added to a `Window` which is manage by `WindowManager`. Read more: http://stackoverflow.com/a/22442702/1798031 – mr.icetea Mar 07 '16 at 12:55