i use different Layouts for different Screensizes and Devices. I use Fragments with specific Layout Folders. The Concept is great, for Tablets and Devices with a Large Screen i place a Layout file in layout-sw600dp and Android manages to deliver the right layout on the different devices.
What Bugs me is: How can i find out what Layout is used inside my Code. My Fragments needs slightly different Codes for the different Layouts.
In General whats the Best Practice to separate Custom Layout Programming Logic inside my Fragments/Activities?
My approach now is kind of hacky and not in sync with the different Layout folders.
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;
}
and then
if(isTabletDevice()) {
//findViewById(R.id.onlyInTabletLayoutButton);
}else{
//
}
This is the method I use personally:
In each layout, I add a Tag to the root of the layout, and make sure that all of the layout roots have the same id. So for example, I'll have a layout that goes something like:
<RelativeLayout
android:id="@+id/rootView"
android:tag="landscapehdpi">
<!-- Rest of layout -->
</RelativeLayout>
And then have another one like:
<RelativeLayout
android:id="@+id/rootView"
android:tag="portraitmdpi">
<!-- Rest of layout -->
</RelativeLayout>
Then once the layout has been inflated, I use:
View rootView = (View) findViewById(R.id.rootView);
This returns the layout root currently in use. Now to determine which layout it is exactly and run the appropriate code, I use a series of if-else blocks:
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...
So basically using this you can know which layout has been loaded at runtime, and run the appropriate code.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With