Search code examples
androidandroid-layoutandroid-custom-viewandroid-button

How can control button Text Size in customized Button class?


I've some buttons in my activity that inflate from a custom class that make the button exact square and fit them in parent depend on screen size and it work's fine :

public class MyButton extends Button {
public MyButton(Context context) {
    super(context);
}

public MyButton(Context context, AttributeSet attrs) {
    super(context, attrs);
}

public MyButton(Context context, AttributeSet attrs, int defStyleAttr) {
    super(context, attrs, defStyleAttr);
}

@Override
public void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {

    super.onMeasure(widthMeasureSpec, widthMeasureSpec);
    int width = MeasureSpec.getSize(widthMeasureSpec);
    int height = MeasureSpec.getSize(heightMeasureSpec);
    int size = width > height ? height : width;
    setMeasuredDimension(size, size); // make it square

}
}

and here my inflater:

LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
Button newGuessButton = (Button) inflater.inflate(R.layout.my_button, currentTableRow, false); 
currentView.addView(newGuessButton);

and layout.xml:

<my.package.name.MyButton
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/newButton"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="100"/>

and my question is how can set text size in my button to change the default size if I want. I think I've to set it before add it as a view but I don't know HOW?


Solution

  • if you just want to set text size you can use attribute

    android:textSize
    

    or use method

    Button.setTextSize()
    

    If you want to fit text inside button you can check this answer