In my application i have this code to calculate phone size and change RecyclerView
layout manager to GridLayoutManager
or LinearLayoutManager
private void changeFeedsLayout() {
// Choose between one, two or three elements per row
if (dpWidth > 720 && getResources().getConfiguration().orientation ==
ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE) {
instagram_feeds.setLayoutManager(new GridLayoutManager(
context, 3, LinearLayoutManager.VERTICAL, false));
} else if (dpWidth > 520) {
instagram_feeds.setLayoutManager(new GridLayoutManager(
context, 2, LinearLayoutManager.VERTICAL, false));
} else {
instagram_feeds.setLayoutManager(new LinearLayoutManager(
context, LinearLayoutManager.VERTICAL, false));
}
}
this code work fine when i attach or commit each fragment to container on MainActivity
, but it doesn't work when in change phone orientation, for fix this problem i'm using this code:
@Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
changeFeedsLayout();
}
and unfortunately layoutmanager of RecyclerView
is LinearLayoutManager
always and i can't resolve that. after switch on other fragment and back to previous fragment work fine.
UPDATE
on change phone orientation this code as:
instagram_feeds.setLayoutManager(new LinearLayoutManager(
context, LinearLayoutManager.VERTICAL, false));
don't work on phone change orientation on changeFeedsLayout()
method and this method couldn't calculate correctly phone size on change phone orientation
This may sound strange, but the only valid solution for this case is to put this settings into resources. Android OS picks up resources basing on lots of properties and one of them is smallest width. To separate list from grid: values/bools.xml:
<resources>
<bool name="is_grid">false</bool>
</resources>
the other one will be values-sw520dp/bools.xml:
<resources>
<bool name="is_grid">true</bool>
</resources>
For number of columns same logic values-sw520dp/integers.xml:
<resources>
<integer name="grid_column_count">2</integer>
</resources>
And values-sw720dp/integers.xml:
<resources>
<integer name="grid_column_count">3</integer>
</resources>
So in code this will be something like:
if (getResources().getBoolean(R.bool.is_grid)) {
instagram_feeds.setLayoutManager(new GridLayoutManager(getActivity(), getResources().getInteger(R.integer.grid_column_count));
} else {
instagram_feeds.setLayoutManager(new LinearLayoutManager(getActivity());
}
This should be applied whenever you create your view, no need to handle config change - it's done for you already. Give the OS do its work.
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