我想知道如何根据设备是平板电脑还是手机来更改活动的主题。我有一个设置活动,其主题为@android:style/Theme.Black.NoTitleBar
。在平板电脑上,我很喜欢这个活动的主题是@android:style/Theme.Dialog
根据设备是Android平板电脑还是手机使用不同的主题
我在Manifest.xml文件中选择了活动的主题,但是我可以看到这个清单文件没有平板版本?
如何更改此活动的主题?我也可能更改其他一些活动的主题,以隐藏操作栏。
我想知道如何根据设备是平板电脑还是手机来更改活动的主题。我有一个设置活动,其主题为@android:style/Theme.Black.NoTitleBar
。在平板电脑上,我很喜欢这个活动的主题是@android:style/Theme.Dialog
根据设备是Android平板电脑还是手机使用不同的主题
我在Manifest.xml文件中选择了活动的主题,但是我可以看到这个清单文件没有平板版本?
如何更改此活动的主题?我也可能更改其他一些活动的主题,以隐藏操作栏。
可以动态设置在每个活动内部像这样:
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;
}
}
您可以在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" />
谢谢,这工作perfekt! – Georg