Akshay Akshay - 1 month ago 11
Android Question

Change RecyclerView's Layout on orientation change

I'm having

RecyclerView
with
GridLayoutManager
. I'm displaying Single Column for landscape and Seven Columns for landscape.
Using:

@Override
public void onConfigurationChanged(Configuration newConfig)
{
recyclerViewCalender.setLayoutManager(new GridLayoutManager(this, newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE ? 7 : 1));
super.onConfigurationChanged(newConfig);
}


But the problem is the Layout used for portrait is not feasible for landscape.
So how can I change the layout of
RecyclerView
on configuration change.
Or is there any other solution for it??

Answer

Here is the solution for this, Pass one Flag to you Adapter which describe current orientation.

@Override
public void onConfigurationChanged(Configuration newConfig)
{
    super.onConfigurationChanged(newConfig);
    //Update the Flag here
    orientationLand = (newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE ? true : false);
}

In your Adapter class:

@Override
public CalenderSessionHolder onCreateViewHolder(ViewGroup parent, int viewType)
{
    //User Flag here to change layou
    View itemView = LayoutInflater.from(parent.getContext()).inflate(orientationLand ? R.layout.item_calender_session_land : R.layout.item_calender_session_port, null);
    return new CalenderSessionHolder(itemView);
}

Make sure you handle the View Id's properly to avoid Exceptions.