Search code examples
androidorientationtext-sizescreen-density

Android - change button text size when orientation changes


I have a button (it is a Bootstrap button, based on com.beardedhen:androidbootstrap).

This is the layout width and height in the xml file:

android:layout_width="0dp"
android:layout_height="wrap_content"

What I want is to modify the text size of the button text when orientation changes (and also be dependent on the various screens sizes).

The reason I want to do this is because on landscape, there is more room to the button rather than in portrait.

I read that onCreate is called each time the orientation changes.

I am using the following code inside onCreate:

DisplayMetrics dm = new DisplayMetrics();
float height = dm.heightPixels;
float width = dm.widthPixels;
BootstrapButton btn = findViewById(R.id.btn);
float density = getResources().getDisplayMetrics().density;
btn.setTextSize((width / density) / 32);

The code calculates the width and the height of the screen and sets the text size accordingly. This way, I get the correct text size based on the device's screen and its orientation (where the width becomes the height and vice-versa).

The problem is that this code doesn't work when the orientation changes.

What am I missing?

Thank you for all the help.


Solution

  • While I don't think this is the best approach, and ConstraintLayouts can help automatically manage the widths.
    But if you want to stick to this approach, try this: Instead of onCreate, try doing this in onConfigurationChanged. Something like:

    Activity Class

    override fun onConfigurationChanged(newConfig: Configuration?) {
        super.onConfigurationChanged(newConfig)
    
        if (newConfig?.orientation == Configuration.ORIENTATION_LANDSCAPE) {
            // Do Landscape calculation
        }
        else {
            // Do Portrait calculation
        }
    }
    

    AndroidManifest.xml
    <activity android:name="[.YourActivity]" android:configChanges="orientation|keyboardHidden|screenSize" />