How to detect the rotation of the screen and change the data of the GridLayoutManager

1

As many of us know that when turning the screen of the phone or tablet what the application does is to load the activity again, I need to detect that turn and change the value of the GridLayoutManager and pass it to the recyclerview, the content that my app loads it does from an xml on a server and the whole process is inside an Asyntask, in the onPostExecute method I created the GridLayoutManager and passed it to the recyclerview. Thanks in advance for the help, I leave part of the code where I need collaboration.

@Override
    protected void onPostExecute(Void aVoid) {
        super.onPostExecute(aVoid);
        progressBar_home.setVisibility(View.INVISIBLE);
        GridLayoutManager gridLayoutManager = new GridLayoutManager(getApplicationContext(), 2);
        mRecycler.setLayoutManager(gridLayoutManager);
        mRecycler.setAdapter(adapter);
    }

I need to pass the spanCount from 2 to 3.

GridLayoutManager gridLayoutManager = new GridLayoutManager(getApplicationContext(), 2);
    
asked by Leonardo Henao 18.11.2017 в 06:17
source

2 answers

2

Thus you determine according to the orientation, size and screen density:

The value you give according to the configuration:

And from java code you invoke it in this way:

@Override
protected void onPostExecute(Void aVoid) {
    super.onPostExecute(aVoid);
    progressBar_home.setVisibility(View.INVISIBLE);
    GridLayoutManager gridLayoutManager = new GridLayoutManager(getApplicationContext(), getResources().getInteger(R.integer.grid_width));
    mRecycler.setLayoutManager(gridLayoutManager);
    mRecycler.setAdapter(adapter);
}
    
answered by 18.11.2017 / 22:52
source
1

What you could do is detect when the screen rotation is done in order to update the adapter of your GridLayout at that particular moment. If you overwrite onConfigurationChanged you will be able to detect the moment in which the user makes a change in the rotation of the screen and thus be able to adapt your application:

@Override
public void onConfigurationChanged(Configuration myConfig) {
    super.onConfigurationChanged(myConfig);
    int orientation = getResources().getConfiguration().orientation;
    Log.d("CHANGESCREEN", "Orientation: " + orientation);
    switch(orientation ) {
        case Configuration.ORIENTATION_LANDSCAPE:
            // Con la orientación en horizontal actualizamos el adaptador
            adapter.notify();
            break;
        case Configuration.ORIENTATION_PORTRAIT:
            // Con la orientación en vertical actualizamos el adaptador
            adapter.notify();
            break;
    }
}
    
answered by 18.11.2017 в 13:08