I'm trying out the new RecyclerView
in combination with the standard implementation of the LayoutManager
the LinearLayoutManager
. My goal is to let the LayoutManager
draw my items horizontally when the device is in portrait orientation and draw them vertically when the device is in landscape. For this I use the following code in my activity's onCreate
:
RecyclerView recyclerView = (RecyclerView) findViewById(R.id.nextColors);
recyclerView.setAdapter(myAdapter = new MyAdapter(getBaseContext(), myData, myLayout);
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
if (getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT) {
linearLayoutManager.setOrientation(LinearLayout.HORIZONTAL);
} else {
linearLayoutManager.setOrientation(LinearLayout.VERTICAL);
}
recyclerView.setLayoutManager(linearLayoutManager);
recyclerView.setItemAnimator(new DefaultItemAnimator());
This works fine if I start the activity while the device is in landscape or portrait mode. But when I change orientation in this activity the items are always drawn horizontally or vertically, depending on the device's orientation when the activity was first started. This doesn't make sense to me since after device rotation the activity is recreated and the LayoutManager
should take the correct orientation.
Does anyone have an idea how to make setOrientation
work with device orientation changes?
This is happening because you are setting orientation before the saved state is restored in RecyclerView.
Try setting orientation on Activity#onPostCreate
or Activity#onResume
(in other words, after saved state is restored) so that saved state won't override your orientation value.
Update As of version 21, LLM will not preserve orientation on configuration changes so your code should work as is. You don't need to care about saved state.
This change is made because saved state should be responsible to save variable state whereas orientation is a configuration which we can expect developer to set each time it is created.
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