简体   繁体   中英

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.

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" />

You should do some reading into Android's Constraint Layout . Inside the layout editor, you can specify constraints on your button, and define how it should look in different layouts and screen sizes.

Also beware, while the code you have written may work, doing manual calculations of screen density is a dangerous and tricky task, and should be avoided if possible. It is for this reason that Android uses dp instead of px . Code like you have written should be used in the cases you must convert between px and dp , or other complicated cases. Something like button resizing depending on screen size is extremely common, and Android provides ways to do this directly inside the layout editor.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM