What is the best way to share different software logic for different layouts in Android?

I use different layouts for different screens and devices. I use fragments with specific layout folders. The concept is great for tablet computers and large-screen devices. I place the layout file in layout-sw600dp , and Android manages to deliver the correct layout on different devices.

What bothers me: how can I find out which layout is used in my code. My snippets need slightly different codes for different layouts.

In general, what is best suited for sharing custom layout programming logic inside my fragments / actions?

My approach is now pretty hacky and out of sync with various 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{
//
}
+5
2

, :

Tag , . , , , :

<RelativeLayout
android:id="@+id/rootView"
android:tag="landscapehdpi">
<!-- Rest of layout -->
</RelativeLayout> 

, :

<RelativeLayout
android:id="@+id/rootView"
android:tag="portraitmdpi">
<!-- Rest of layout -->
</RelativeLayout> 

, , :

View rootView = (View) findViewById(R.id.rootView);

, . , , , 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...

, , , .

+2

All Articles