45

How to change the width of a Button programmatically. I am able to change the height but the width does not change. Following is my code snippet

private void createButton(final String label)
{

    Button button = new Button(this);
    button.setText(label);


    button.setWidth(10);
    button.setHeight(100);

    button.setOnClickListener(new OnClickListener() 
    {

        @Override
        public void onClick(View v) 
        {


        }
    });
    mMenuContainer.addView(button, mMenuItemLayoutParamters);


}

But the width of the Button occupies the width of the screen.

CopsOnRoad
  • 237,138
  • 77
  • 654
  • 440
Joyson
  • 1,643
  • 5
  • 28
  • 48

8 Answers8

96

button.setLayoutParams(new LinearLayout.LayoutParams(10, 100));

Should have work for you.

There is one Awesome Example online for this : check this


you should apply LayoutParams of the ViewGroup that contains your View. That is, if your button is inside RelativeLayout, you should use RelativeLayout.LayoutParams

MKJParekh
  • 34,073
  • 11
  • 87
  • 98
  • 4
    important to note: you should apply `LayoutParams` of the `ViewGroup` that contains your `View`. That is, if your button is inside `RelativeLayout`, you should use `RelativeLayout.LayoutParams`. – agamov Apr 09 '14 at 07:04
  • 1
    You should multiply your size values by the display scale, because the constructor takes pixels, not dp. Like so: widthInPixels = getResources().getDisplayMetrics().density * widthInDp; – Uwe Post Nov 11 '15 at 14:52
  • 1
    The recommendation about using the correct ViewGroup must be followed. If you use an incorrect VG, the app will crash and logcat will have zero information on the reason – Jose_GD Dec 21 '16 at 19:13
  • 1
    I wonder why setWIdth() and setHeight() are even offered for buttons and textviews when they don't appear to work in practice, including for myself. I see dozens of 'Question: setWIdth() doesn't work, Answer: use LayoutParams' on this site. – Androidcoder Oct 08 '17 at 21:33
  • 1
    For Kotlin programmers, it should work like this: `button.layoutParams = LinearLayout.LayoutParams(10, 100)` – Jens van de Mötter May 25 '20 at 22:39
48

you can do it this way.

LinearLayout.LayoutParams params = button.getLayoutParams();
params.width = 100;
button.setLayoutParams(params);

but make sure you do this, after adding your button to a parent. and LinearLayout.LayoutParams is used when parent is a LinearLayout and when parent is RelativeLayout use RelativeLayout.LayoutParams.

Aqif Hamid
  • 3,511
  • 4
  • 25
  • 38
  • Setting a width can set "px" value or "dp" and how can we change it into dp if we set dp value on XML at the first beginner value, for example width="50dp" ? – Bay Jun 03 '22 at 21:13
3
ConstraintLayout.LayoutParams layoutParams = (ConstraintLayout.LayoutParams) yourButton.getLayoutParams();
layoutParams.width = 150;
yourButton.setLayoutParams(layoutParams);

the "ConstraintLayout" can change up to your layout and set size by "layoutParams.width". This case it's work for me!

INZIXI
  • 31
  • 2
2

can do this

    int width= (int)getResources().getDimension(R.dimen.button_width);
    int heigth= (int)getResources().getDimension(R.dimen.button_heigth);
    ViewGroup.LayoutParams layoutParams = new ViewGroup.LayoutParams(width, heigth);
    button.setLayoutParams(layoutParams);
Cícero Moura
  • 2,027
  • 1
  • 24
  • 36
2

I solved by using this:

//ImageButton creation
final ImageButton server_icon_button=new ImageButton(getApplicationContext());
//setting background image in drawable
server_icon_button.setBackgroundResource(R.drawable.bonsai);
//After adding ImageButton to the parent i done this
server_icon_button.getLayoutParams().height=180;
server_icon_button.getLayoutParams().width=100;

I hope this help.

1

In my case I am using AppCompatImageButton (and AppCompat). It turns out that if I keep density adjusted images in the various drawable folders: drawable-ldpi, drawable-mdpi, drawable-hdpi, etc.. then the button won't scale. Instead I had to put a single drawable for each button in drawable-nodpi. Make sure the drawable-nodpi button image is of the largest size you need. Android will not scale the button size up; however, it can scale the size down. I created a button in XML like this:

<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:meter="http://schemas.android.com/apk/res-auto"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content">

    <android.support.v7.widget.AppCompatImageButton
        android:id="@+id/button"
        style="@style/ButtonStyle"
        android:baselineAlignBottom="true"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:minHeight="0dp"
        android:minWidth="0dp"
        app:srcCompat="@drawable/button_selector"
        android:background="?attr/selectableItemBackgroundBorderless"
        android:contentDescription="@string/button"
        android:focusable="true">
</RelativeLayout>

<!-- styles.xml -->
<style name="ButtonStyle" parent="MyAppTheme">
    <item name="android:scaleType">centerInside</item>
    <item name="android:adjustViewBounds">true</item>
    <item name="colorControlHighlight">@color/buttonColorPressed</item>
    <item name="colorButtonNormal">@color/buttonColor</item>
</style>

<!-- v21/styles.xml -->
<style name="TargetButton" parent="MyAppTheme">
    <item name="android:scaleType">centerInside</item>
    <item name="android:adjustViewBounds">true</item>
    <item name="colorControlHighlight">@color/buttonColorPressed</item>
    <item name="colorButtonNormal">@color/buttonColor</item>
    <item name="android:elevation">@dimen/button_elevation</item>
</style>

<!-- drawable/button_selector.xml -->
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:drawable="@drawable/button_pressed" android:state_pressed="true"/>
    <item android:drawable="@drawable/button"/>
</selector>

<!-- drawable/button.xml -->
<bitmap xmlns:android="http://schemas.android.com/apk/res/android"
      android:src="@drawable/ic_button"
      android:gravity="center" />

<!-- drawable/button_pressed.xml -->
<bitmap xmlns:android="http://schemas.android.com/apk/res/android"
      android:src="@drawable/ic_button_pressed"
      android:gravity="center" />

Next, in onCreate when you retrieve the button, call adjustButtonSize (which i put in my base class):

    mButton = (AppCompatImageButton) findViewById(R.id.button);
    adjustButtonSize(mButton);

public void adjustButtonSize(AppCompatImageButton button) {
    DisplayMetrics displayMetrics = getResources().getDisplayMetrics();
    int width = displayMetrics.widthPixels;
    int height = displayMetrics.heightPixels;
    ViewGroup.LayoutParams params = button.getLayoutParams();
    params.height = height / 10;         // 10%
    params.width = ((width * 20) / 100); // 20%
    button.setLayoutParams(params);
}
Lee Hounshell
  • 842
  • 9
  • 10
0

Try using only mMenuContainer.addView(button);

StarsSky
  • 6,721
  • 6
  • 38
  • 63
Niko
  • 8,093
  • 5
  • 49
  • 85
0

You can try out this kotlin code.

This is great when you want to give the size of another view to some other view.

class MainActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        equalToButton.post(Runnable { zeroButton.height = equalToButton.height })
    }
}
Anirudha Mahale
  • 2,526
  • 3
  • 37
  • 57