Saturday, March 21, 2015

Android - Detecting Config Changes in an Activity

As part of the project, had to have a Grid view and the grid view had to have 3 columns in landscape while only 2 columns in portrait mode. Implementing this was fairly simple and mainly two steps to do this:

1. Declare the Activity for accepting the configuration changes 
2. once the configuration changed is called back, set the grid column to the number desired 

Below is the code snippet to be placed in the activity for declaring config changes. 


 
            android:name=".MainActivity"
            android:label="@string/app_name"
            android:configChanges="orientation|screenSize">
       

Note that if we have only “orientation” in the value, then the callback was not happening, had to give screenSize as well. 

in the app, below is the code 

@Override
    public void onConfigurationChanged(Configuration newConfig) {
        Log.v("RR:--","Main activity onConfigurationChanged "+newConfig);
        GridView gridview = (GridView) findViewById(R.id.gridview);
        if(gridview != null) {
            gridview.setNumColumns(newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE ? 3 : 2);
            super.onConfigurationChanged(newConfig);
        }
    }

references: 

No comments:

Post a Comment