Mic*_*ele 5 android android-layout
我为不同的屏幕尺寸和设备使用不同的布局.我将片段与特定的布局文件夹一起使用.这个概念很棒,对于平板电脑和大屏幕设备,我将布局文件放在 layout-sw600dp中,Android设法在不同的设备上提供正确的布局.
我的错误是:如何找到我的代码中使用的布局.我的片段需要稍微不同的代码用于不同的布局.
总的来说,在我的片段/活动中分离自定义布局编程逻辑的最佳实践是什么?
我的方法现在有点hacky并且与不同的Layout文件夹不同步.
private boolean isTabletDevice() {
if (android.os.Build.VERSION.SDK_INT >= 11) { // honeycomb
// test screen size, use reflection because isLayoutSizeAtLeast is
// only available since 11
Configuration con = getResources().getConfiguration();
try {
Method mIsLayoutSizeAtLeast = con.getClass().getMethod("isLayoutSizeAtLeast", int.class);
Boolean r = (Boolean) mIsLayoutSizeAtLeast.invoke(con, 0x00000004); // Configuration.SCREENLAYOUT_SIZE_XLARGE
return r;
} catch (Exception x) {
x.printStackTrace();
return false;
}
}
return false;
}
Run Code Online (Sandbox Code Playgroud)
然后
if(isTabletDevice()) {
//findViewById(R.id.onlyInTabletLayoutButton);
}else{
//
}
Run Code Online (Sandbox Code Playgroud)
这是我个人使用的方法:
在每个布局中,我将一个标签添加到布局的根,并确保所有布局根具有相同的 id。例如,我的布局如下:
<RelativeLayout
android:id="@+id/rootView"
android:tag="landscapehdpi">
<!-- Rest of layout -->
</RelativeLayout>
Run Code Online (Sandbox Code Playgroud)
然后再有一个这样的:
<RelativeLayout
android:id="@+id/rootView"
android:tag="portraitmdpi">
<!-- Rest of layout -->
</RelativeLayout>
Run Code Online (Sandbox Code Playgroud)
然后,一旦布局膨胀,我使用:
View rootView = (View) findViewById(R.id.rootView);
Run Code Online (Sandbox Code Playgroud)
这将返回当前正在使用的布局根。现在,为了确定它到底是哪种布局并运行适当的代码,我使用了一系列 if-else 块:
String tag = rootView.getTag().toString();
if(tag.equals("landscapehdpi"))
{
//Code for the landscape hdpi screen
}
else if(tag.equals("portraitmdpi"))
{
//Code for the portrait mdpi screen
}
//And so on...
Run Code Online (Sandbox Code Playgroud)
所以基本上使用这个你可以知道在运行时加载了哪个布局,并运行适当的代码。