How do I make several different screen configurations for a small set of layouts without duplicating parts of my XML layout?

My application displays either a single-level user interface or a two-level interface depending on the screen configuration. On small screens, it should be single-layer both in portrait and landscape. On medium screens (anything with a "smallest width" of 600dp or higher), the landscape orientation is ideal for a two-panel layout, but for portrait orientation it should use a single-level layout. On large screens, he should use a two-panel layout for both orientations. I also want to support 3.2+ style qualifiers (for example, sw600dp and sw720dp), as well as the older size classifier ("xlarge").

The most direct way to do this is to create several different XML layout files, one for each configuration:

  • Res / layout sw600dp-earth / main.xml
  • Res / layout sw600dp-port / main.xml
  • Res / layout sw720dp-earth / main.xml
  • Res / layout sw720dp port / main.xml
  • Res / Layout XLarge-port / main.xml
  • Res / Layout XLarge-ground / main.xml
  • Res / port layout /main.xml
  • Res / layout / main.xml

As a result, there are many duplicates of the code in these 8 XML files, which essentially describe only two different layouts.

How can I do this without having to maintain all of these duplicate XML files, which are a maintenance headache?

+6
source share
1 answer

You can use layout aliases. Instead of describing your layout directly in the XML files for each screen configuration, you should define your two layouts in two XML files, for example, "onepane.xml" and "twopanes.xml". These files go to res / layout.

Now you need to map these layouts to your other screen configuration and where the “alias layout” technique comes in handy. For each combination of screen qualifiers, create an XML file in res / values-X / layout.xml, where X is the combination of qualifiers. In this file, declare a layout resource that points to: @ layout / onepane or @ layout / twopanes, depending on the situation:

RES / values-sw600dp-earth / layout.xml:

<resources> <item name="main" type="layout">@layout/twopanes</item> </resources> 

RES / values-sw600dp-port / layout.xml:

 <resources> <item name="main" type="layout">@layout/onepane</item> </resources> 

Do the same for your other configuration combinations, and this way you can accomplish what you are looking for: you can map two layouts (single-panel and two-position) to several different screen configurations without having to duplicate your layout.

For more information on this, check out the “Multi-Screen Support” lesson in Android Training: http://developer.android.com/training/multiscreen/screensizes.html#TaskUseAliasFilters

+11
source

Source: https://habr.com/ru/post/912436/


All Articles