See Supporting Different Screen Sizes.
Typically this is done using Fragments, but the basic idea is the same whether you use fragments or not. You create two different layouts for your Activity depending on the screen size.
- Save the default layout single-pane for phones at
res/layout/activity_main.xml
- Save the dual-pane tablet layout at
res/layout/activity_main_twopane.xml
Then you use layout alias files with the screen size qualifiers described in the link to determine when the tablet layout should be used. For example to show the dual-pane layout on large
screens and on screens with at least 600dp in the widest direction (includes large screen phones such as the Galaxy S3), you could do this:
res/values-large/layout.xml
contains:
<resources>
<item name="activity_main" type="layout">@layout/activity_main_twopane</item>
<bool name="twopane">true</bool>
</resources>
res/values-sw600dp/layout.xml
contains:
<resources>
<item name="activity_main" type="layout">@layout/activity_main_twopane</item>
<bool name="twopane">true</bool>
</resources>
The Android system will take care of loading the proper layout file (either res/layout/activity_main.xml
or res/layout/activity_main_twopane.xml
) when your Activity loads the layout:
setContentView(R.layout.activity_main);
Just remember that the views that don't exist in the single-pane layout will be null when you try to access them (e.g., there won't be two ListView
s anymore). Checking whether a certain View exists is one way to detect which layout you are using.
Also note the use of optional Boolean resources in XML files. This is a handy way to pass the "is it a large screen or small screen" variable to your Java code. You can access Boolean resources in your Activity like this:
boolean isTwoPane = getResources().getBoolean(R.bool.twopane);