Use a different theme depending on whether the device is an Android tablet or a phone

I was wondering how I can change the subject of an action depending on whether the device is a tablet or a phone. I have a settings activity in which there is an @android:style/Theme.Black.NoTitleBar theme @android:style/Theme.Black.NoTitleBar . On a tablet, I would like the theme of this activity to be something like @android:style/Theme.Dialog

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

How can I change the subject for this activity? I can also change the theme for some other actions, as well as hide the action bar.

+6
source share
2 answers

You can set it dynamically inside each action as follows:

  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 the isTablet method, but determining the type of device is a bit difficult. Here is a method that I found on the Internet, it checks the screen size, and if the screen is large, it is assumed that the 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; } } 
+9
source

You can describe a custom theme (which can simply point to a default theme) in the form of a typing resource file , and then refer to this theme in the manifest.

Then you can provide alternative resources based on some criteria (just like with pins of different densities, but now you must specify the minimum screen size or, for example, API).

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" /> 
+10
source

Source: https://habr.com/ru/post/901599/


All Articles