使用不同的主题取决于如果设备是Android平板电脑或手机 [英] Use different theme depending on if device is android tablet or phone
问题描述
我想知道我可以改变这取决于活动的主题,如果该设备是平板电脑或手机。我有一个设置的活动,有一个 @android:款式/ Theme.Black.NoTitleBar
主题吧。在数位板上我喜欢这个活动的主题是这样的 @android:款式/ Theme.Dialog
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
我选择在Manifest.xml文件活动的主题,但我可以看到有这个清单文件中没有平板电脑的版本?
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.
推荐答案
您可以动态每项活动像这里面的设置
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);
}
现在你需要 isTablet
方法,但它是一个有点难以察觉的设备类型。这里有一个方法,我在网上找到,它会检查屏幕尺寸,如果屏幕大它假定当前设备是平板电脑:
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;
}
}
这篇关于使用不同的主题取决于如果设备是Android平板电脑或手机的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!