Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to change button size programmatically in Android?

Tags:

android

button

I am creating buttons and adding them to a LinearLayout programmatically. However, I am struggling with changing the button sizes. In the code below, no matter what num I enter in deleteBtn.setWidth(num), and deleteBtn.setHeight(num), nothing changes.

private void populateHorizontalLayouts(CustomMessageEvent event) {
    // Need to remove all views each time an user adds a number
    // so that the same number is not rendered multiple times.

    nameAndNumbersLayout.removeAllViews();

    //displayedNamesAndNumbers.add(event.getCustomMessage());
    for(int i =0; i < displayedNamesAndNumbers.size(); i++){
        String displayedNumberAndName = displayedNamesAndNumbers.get(i);

        LinearLayout horizontalLayout = new LinearLayout(view.getContext());
        horizontalLayout.setOrientation(LinearLayout.HORIZONTAL);
        horizontalLayout.setId(i);

        Button deleteBtn = new Button(view.getContext());
        deleteBtn.setId(i);
        deleteBtn.setText("Delete");
        deleteBtn.setWidth(5);
        deleteBtn.setHeight(5);

        TextView nameAndNumView = new TextView(view.getContext());
        nameAndNumView.setId(i);
        nameAndNumView.setText(displayedNumberAndName);

        horizontalLayout.addView(deleteBtn);
        horizontalLayout.addView(nameAndNumView);

        nameAndNumbersLayout.addView(horizontalLayout);
    }
}

What should I write so that the button size changes?

like image 922
Nora Avatar asked Dec 06 '22 11:12

Nora


2 Answers

You should apply LayoutParams of the LinearLayout which contains your Button.

deleteBtn.setLayoutParams(new LinearLayout.LayoutParams(5, 5));
like image 200
Hossein Seifi Avatar answered Dec 27 '22 17:12

Hossein Seifi


Try this one

deleteBtn.setLayoutParams (new LayoutParams(LayoutParams.MATCH_PARENT, 15));
like image 20
Manish Mahajan Avatar answered Dec 27 '22 17:12

Manish Mahajan