There is two things to develop this functionnality.
First you will have to make two different layouts:
res
|- layout
|- mylayout.xml
|- layout-land.xml
|- mylayout.xml
In the layout/mylayout.xml
file, include a ListView
where you need it and in layout-land/mylayout.xml
, include your GridView
.
Android will select automatically the correct layout, depending of the current screen orientation, when you call setContentView
.
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.mylayout);
mListView = (ListView) findViewById(R.id.mylistview);
mGridView = (GridView) findViewById(R.id.mygridview);
// !!!!!!!
// mListView will be null in landscape
// mGridView will be null in portrait
// !!!!!!!
}
setContentView(R.layout.mylayout);
Now, in code you will need to check in which orientation you are to make if/else statements.
To detect in which orientation you are, follow the following states:
create a file in res/values/bool.xml
<resources>
<bool name="isLandscape">false</bool>
</resources>
create a file in res/values-land/bool.xml
<resources>
<bool name="isLandscape">true</bool>
</resources>
Now in your activity you can easily test, every time you need, if you are in landscape or portrait mode and apply the corresponding action
boolean landscape = getResources().getBoolean(R.bool.isLandscape);
if (landscape) {
// do something with your GridView
} else {
// do something with your ListView
}
To respond to your edit:
Fragments are very similar to Activities for this.
If you want to save data during orientation change, follow the official documentation on this topic, especially the part on Retaining an Object During a Configuration Change.
You should not use the android:configChanges
in Manifest as explained in the documentation:
Handling the configuration change yourself can make it much more
difficult to use alternative resources, because the system does not
automatically apply them for you. This technique should be considered
a last resort when you must avoid restarts due to a configuration
change and is not recommended for most applications.