Skip to content Skip to sidebar Skip to footer

How To Programmatically Make A Small Button Wrap Small Text

I want to make small buttons, So far I have made the text small but there is still alot of space around the text. I have tried the code below: LinearLayout layout = (LinearLay

Solution 1:

in eclipse write your button name. txtName then many options will come for you and choose whatever you want. or use developer's website.

Button txtName = new Button(getActivity(), null, android.R.attr.buttonStyleSmall);
    txtName.setClickable(false);
    txtName.setHeight(17);
    txtName.setWidth(25);
    txtName.setTextSize(10);
    txtName.setMaxLines(1);
    txtName.setMaxHeight(5);
    txtName.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT));

    txtName.setText(tagsList.get(i));
    layout.addView(txtName);

Solution 2:

Here is a solution:

...
Button b = new Button(getContext());
b.setText("Text");
b.setPadding(dpToPx(5), 0, dpToPx(5), 0);
// crazy I have to set both of these?...
b.setMinWidth(0);
b.setMinimumWidth(10);
b.setTextSize(TypedValue.COMPLEX_UNIT_SP, 10);
LinearLayout.LayoutParams params = new 
LinearLayout.LayoutParams(LinearLayout
                .LayoutParams.WRAP_CONTENT, dpToPx(20));
b.setLayoutParams(params);
...

publicstaticintdpToPx(int dp) {
    return (int) (dp * Resources.getSystem().getDisplayMetrics().density);
}

Solution 3:

txtName.setHeight(20);
txtName.setWidth(20);

Solution 4:

You should use fixed size (equal min and max values for width or height)

Code:

btn.setMaxHeight(40);
btn.setMinHeight(40);
btn.setMaxWidth(40);
btn.setMinimumWidth(40);

XML:

android:maxHeight="40dp"android:minHeight="40dp"android:maxWidth="40dp"android:minWidth="40dp"

Post a Comment for "How To Programmatically Make A Small Button Wrap Small Text"