Search code examples
androidandroid-layoutandroid-studioscreen-sizeandroid-screen-support

Android button size changes at different devices (width is set to dp)


I am designing an app which needs the customized button. I made it by inheriting the Android Button and I set its width to 300dp in the layout xml. However, I found the size of button is changing on different devices. Here are the example:

My UI in the original device: Galaxy S5

My UI in the new device: Nexus 5X

My UI in another device: Galaxy Note4 (In this trial, I set the left button to use sp instead of dp)

It seems the whole layout scale is smaller in my new device even though both of them are 1080 x 1920 pixels.

I also try to use sp but it behaves the same (problem). My guess is the style? Can any one gives me more thoughts. Thanks!

--- UPDATE --- Hi, let me rephrase my problem.

I am looking for a way to make a button which width is fix to like (relatively) 1/3 screen width at any device. And its text also changes accordingly. I think the ultimate way is to translate everything to pixel and assign those value manually in program. I used to think using dp and sp is an easy alternative to achieve it, but it turns out not :(


Solution

  • To set width of each child programmaticaly,

    view.getLayoutParams().width = getScreenWidth() / VIEWS_COUNT_TO_DISPLAY;
    

    And Screensize as below

    DisplayMetrics metrics = new DisplayMetrics();
    getWindowManager().getDefaultDisplay().getMetrics(metrics).widthPixels;
    

    Now, If you want to set Text than use SP for that.