Skip to content Skip to sidebar Skip to footer

How To Re-position The Grid Layout Elements In Fragments On Orientation Change?

I am having a bottom tabbed activity with three fragments Home, Dashboard and Notifications. In the first fragment, I am having 4 layouts with a button in each layout. These 4 layo

Solution 1:

Target API 13+:

Set the android:configChanges flag in your Activity in manifest.xml

<activityandroid:name="com.test.activity.MainActivity"android:configChanges="orientation|screenSize|keyboardHidden"/>

Solution 2:

You need to have two different layouts for portrait and landscape orientation.

it should be named same name, but in different layout directories:

layout dir where your current layout is for Portrait orientation.

Now create layout-land directory, copy same layout and refactor it with same view id's just different positions.

It should look like this:

enter image description here

Solution 3:

I would suggest use RecyclerView pattern with different spanCount after rotation configuration changes.

Also you can calculate span count by screen width or whatever.

So basically in onCreate(), set new GridLayoutManager(context, GRID_SPAN_COUNT_BY_ROTATION) in toRecyclerView

it should look like this in your fragment:

public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        homeViewModel = ViewModelProviders.of(this).get(HomeViewModel.class);
        Viewroot= inflater.inflate(R.layout.fragment_home, container, false);
        RecyclerViewrecyclerView= root.findViewById(R.id.your_recyclerview);


        // set span count by orientationintorientation= getResources().getConfiguration().orientation;
        int spanCount;
        if (orientation == Configuration.ORIENTATION_PORTRAIT) {
            // code for portrait mode
            spanCount = 4;
        } else {
            // code for landscape mode
            spanCount = 9;
        }

        // set GridLayoutManager with custom span count
        recyclerView.setLayoutManager(newGridLayoutManager(context, spanCount));

        homeViewModel.getText().observe(this, newObserver<String>() {
            @OverridepublicvoidonChanged(@Nullable String s) {
            }
        });
        return root;
    }

if it is not working then do not forget to change manifest config rules like mentioned in another answer.

Post a Comment for "How To Re-position The Grid Layout Elements In Fragments On Orientation Change?"