Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use different theme depending on if device is android tablet or phone

Tags:

android

I was wondering how I can change the theme of an activity depending on if the device is a tablet or a phone. I have a settings activity that has a @android:style/Theme.Black.NoTitleBar theme to it. On the tablet I'd love the theme of this activity to be something like @android:style/Theme.Dialog

I chose the theme of the activity in the Manifest.xml file, but as I can see there is no tablet version of this manifest file?

How can I change the theme for this activity? I might also change the theme for some other activities as well to hide the action bar.

like image 931
Georg Avatar asked Nov 16 '11 08:11

Georg


2 Answers

You can set it dynamically inside each activity like this:

 protected void onCreate(Bundle icicle) {

    super.onCreate(icicle);

    // ...

    // Call setTheme before creation of any(!) View.

    if(isTablet()) {
        setTheme(android.R.style.Black);
    }
    else {
        setTheme(android.R.style.Theme_Dark);
    }     
    // ...

    setContentView(R.layout.main);
}

Now you need isTablet method but it is a bit difficult to detect device type. Here is a method I found online, it checks the screen size and if the screen is big it assumes current device is a tablet.:

public boolean isTablet() {
    try {
        // Compute screen size
        DisplayMetrics dm = context.getResources().getDisplayMetrics();
        float screenWidth  = dm.widthPixels / dm.xdpi;
        float screenHeight = dm.heightPixels / dm.ydpi;
        double size = Math.sqrt(Math.pow(screenWidth, 2) +
                                Math.pow(screenHeight, 2));
        // Tablet devices should have a screen size greater than 6 inches
        return size >= 6;
    } catch(Throwable t) {
        Log.error(TAG_LOG, "Failed to compute screen size", t);
        return false;
    }

} 
like image 196
Caner Avatar answered Jan 04 '23 06:01

Caner


You can describe a custom theme (which might simply point to a default theme) in a style resource file, and then reference that theme in the Manifest.

Then, you could provide alternative resources based on some criteria (just like with drawables of different density, but now you would specify minimum screen size or API level for example).

Manifext:

<application android:theme="@style/CustomTheme">

res/values/styles.xml:

<style name="CustomTheme" parent="android:Theme.Black.NoTitleBar" />

res/values-v11/styles.xml:

<style name="CustomTheme" parent="android:Theme.Dialog" />
like image 41
ron Avatar answered Jan 04 '23 06:01

ron