【问题标题】:Use different theme depending on if device is android tablet or phone根据设备是安卓平板电脑还是手机使用不同的主题
【发布时间】:2014-06-04 06:48:38
【问题描述】:

我想知道如何根据设备是平板电脑还是手机来更改活动的主题。我有一个带有@android:style/Theme.Black.NoTitleBar 主题的设置活动。在平板电脑上,我希望这个活动的主题类似于@android:style/Theme.Dialog

我在 Manifest.xml 文件中选择了活动的主题,但我可以看到这个清单文件没有平板电脑版本?

如何更改此活动的主题?我也可能会更改一些其他活动的主题以隐藏操作栏。

【问题讨论】:

    标签: android


    【解决方案1】:

    您可以像这样在每个活动中动态设置它:

     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);
    }
    

    现在您需要isTablet 方法,但检测设备类型有点困难。这是我在网上找到的一种方法,它会检查屏幕尺寸,如果屏幕很大,则假定当前设备是平板电脑。:

    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;
        }
    
    } 
    

    【讨论】:

      【解决方案2】:

      您可以在 style resource file 中描述自定义主题(可能只是指向默认主题),然后在清单中引用该主题。

      然后,您可以根据某些条件提供alternative resources(就像使用不同密度的可绘制对象一样,但现在您可以指定最小屏幕尺寸或 API 级别)。

      清单:

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

      【讨论】:

      • 感谢您的想法。主要问题是我希望特定的 Activity 是基于设备是否是平板电脑的对话框或全屏活动。在手机上,活动将在标签栏中,在平板电脑上,它是一个对话框。有了你的解决方案,我看不出我怎么能做到这一点。
      • @Georg:您可以尝试为特定的 元素指定 android:theme。
      • 你的意思是我应该为每个活动设置一个主题,并在 values-xlarge/style.xml 中“覆盖”平板电脑所需的主题?
      • @Georg:这听起来是一个选择,您可以选择使用代码还是 xml。
      • 我同意@Georg,您也可以使用 api 版本和屏幕尺寸的组合,例如。 values-v11-xlarge
      猜你喜欢
      • 2014-12-26
      • 1970-01-01
      • 1970-01-01
      • 2012-07-05
      • 1970-01-01
      • 2016-11-09
      • 1970-01-01
      • 1970-01-01
      • 2015-05-28
      相关资源
      最近更新 更多