2011-11-16 48 views
6

我想知道如何根据设备是平板电脑还是手机来更改活动的主题。我有一个设置活动,其主题为@android:style/Theme.Black.NoTitleBar。在平板电脑上,我很喜欢这个活动的主题是@android:style/Theme.Dialog根据设备是Android平板电脑还是手机使用不同的主题

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

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

回答

9

可以动态设置在每个活动内部像这样:

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

} 
+0

谢谢,这工作perfekt! – Georg

10

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

然后,您可以基于某些条件提供alternative resources(就像绘制不同密度的绘图一样,但现在您将指定最小屏幕大小或API级别)。

Manifext:

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

RES /价值/ styles.xml:

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

RES /值-V11/styles.xml:

<style name="CustomTheme" parent="android:Theme.Dialog" /> 
+0

感谢您的想法。主要的问题是,我只想根据设备是否为平板电脑,将特定活动设置为对话框或全屏活动。在电话中,活动将位于标签栏中,在平板电脑上是对话框。 随着你的解决方案,我看不出我能做到这一点。 – Georg

+1

@Georg:您可以尝试为特定的元素指定android:主题。 – ron

+0

你的意思是我应该为每个活动设置一个主题,并在值-xlarge/style.xml中“覆盖”我需要的平板电脑的主题? – Georg

相关问题