Search code examples
androidsizedensity-independent-pixel

How to programmatically alter an apps size, with DIP instead of PX


I've searched and found an exceptional amount of answers to this, but none that will show how they are inserted into the activity.

My activity has a tabsadapter and viewpager (fragmentpageradapter). That's it. And I've set it to be styled as a dialog, like this

    <style name="Theme.PopupTheme" parent="android:Theme.Holo.Light.Dialog">
    <item name="android:windowIsFloating">false</item>
    <item name="android:windowContentOverlay">@null</item>
    <item name="android:windowSoftInputMode">stateAlwaysHidden</item>
    <item name="android:windowActionModeOverlay">true</item>
    <item name="android:windowIsTranslucent">true</item>
    <item name="android:windowNoTitle">false</item>
    <item name="android:windowActionBar">true</item>
    <item name="android:backgroundDimEnabled">true</item>
    <item name="android:padding">2sp</item>
    <item name="android:divider">@drawable/transparent</item>

Now, this works just fine except that it takes up the full size of the display with barely any transparency on the sides and bottom. There is no layout for this activity, just a viewpager xml

<android.support.v4.view.ViewPager xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/viewPager"
    android:layout_width="match_parent"
    android:layout_height="match_parent" />

Because of this I'm tied to sizing the app programmatically. I found that I can only manage this (with my level of skill) by setting it with pixels. Which can look good if it was meant for a certain device, but the app looks atrocious on my Nexus 10 compared to my S3 when and vice-versa depending on the amount of pixels I set.

How can I do this programmatically with dip?


Solution

  • I don't think there's a way to set it directly in dip.

    You can use this method to convert from dip to px and use the result to size the view.

    private static float scale = 0;
    ...
    public static int dps2pixels(int dps, Context context) {
        if (0 == scale) {
            scale = context.getResources().getDisplayMetrics().density;
        }
        return (int) (dps * scale + 0.5f);
    }