Michiel
Michiel

Reputation: 120

Android button drawable does not fit the text

For my app I want to add buttons to a linearlayout programmatically with a background to make it look better. For the background I use a drawable. The drawable is defined as:

<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="rectangle">
    <solid android:color="@color/colorPrimary" />
    <corners
        android:bottomRightRadius="24dp"
        android:bottomLeftRadius="24dp"
        android:topRightRadius="24dp"
        android:topLeftRadius="24dp"/>
</shape>

The button is defined programaticaly by:

//make new button
Button b = new Button(this);
b.setText(someText);
b.setId(id);
b.setAllCaps(false);
b.setTextColor(getResources().getColor(R.color.textOnButton));
b.setBackground(drawable);
b.setOnClickListener(new View.OnClickListener() {
    public void onClick(View v) {
        doAction(v);
    }
});

//setParameters of Linearlayout
LinearLayout linear = findViewById(R.id.linearLayout);
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
    LinearLayout.LayoutParams.MATCH_PARENT, BUTTON_HEIGHT);
params.setMargins(LEFT_MARGIN_BUTTON, TOP_MARGIN_BUTTON,RIGHT_MARGIN_BUTTON,DOWN_MARGIN_BUTTON);
linear.setOrientation(LinearLayout.VERTICAL);

//add button to linearlayout
linear.addView(b, params);

However, if I make a button with this drawable as background, it will appear as: error button

The white mess in the middle is some text that should appear as something like this: correct text button

Idealy I would like to change the height of the button to the default textsize of the system plus some margin. Is there way to fix this?

Upvotes: 2

Views: 84

Answers (2)

Michiel
Michiel

Reputation: 120

Another way to fit this purpose is to use:

//first acquire the default text height
int textSize = (int) new Button(this).getTextSize();

//then set the height of the layout to this default text height plus some constant
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
     LinearLayout.LayoutParams.MATCH_PARENT,
     textSize + BUTTON_TEXT_MARGIN);

Upvotes: 0

Gabriele Mariotti
Gabriele Mariotti

Reputation: 364988

Use:

LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
    LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);

In your case you can also use a simple MaterialButton:

 val b = MaterialButton(this)
 b.cornerRadius = resources.getDimensionPixelOffset(R.dimen.cornerSize)

enter image description here

Upvotes: 1

Related Questions