0

I'm using Recyclerview in fragment... Inside my fragment I'm setting my GridLayout in the following way:

myTV.setLayoutManager(new GridLayoutManager(getActivity(),3));

code says,Only 3 columns for Landscape and Portrait mode.

But I want to maximum no.of column for screen fit for when the user rotates the phone/tablet....

Here is my PeopleFragment.java

public class PeopleFragment extends Fragment {
    View v;
        List<People> listPeople;
        @Override
        public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
            v= inflater.inflate(R.layout.fragment_people,container,false);

            listPeople = new ArrayList<>();

            listPeople.add(new People("1-name",R.drawable.image1));
            listPeople.add(new People("2-name",R.drawable.image2));
            listPeople.add(new People("3-name",R.drawable.image3));
            listPeople.add(new People("4-name",R.drawable.image4));
            listPeople.add(new People("5-name",R.drawable.image5));
            listPeople.add(new People("6-name",R.drawable.image6));
            listPeople.add(new People("7-name",R.drawable.image7));

            RecyclerView myTV= (RecyclerView) v.findViewById(R.id.recyclerview_id);
            RecyclerViewAdapterPDF myAdapter = new RecyclerViewAdapterPDF(getActivity(),listPeople);
            myTV.setLayoutManager(new GridLayoutManager(getActivity(),3));
            myTV.setAdapter(myAdapter);

            return v;
      }
    }

fragment_people.java

 <android.support.v7.widget.RecyclerView
            android:id="@+id/recyclerview_id"
            android:layout_width="match_parent"
            android:layout_height="match_parent"></android.support.v7.widget.RecyclerView>

I used android:numColumns="auto_fit". but I's not working....

Could you tell me how to solve this issue?Here is different question...

Markus Kauppinen
  • 3,025
  • 4
  • 20
  • 30
Mr.Soft
  • 143
  • 2
  • 14

1 Answers1

4

Check this for better solution

Here you can create one class for return no of columns or use methods directly..

Add this method to your fragment class..

public int calculateNoOfColumns(Context context) {
    DisplayMetrics displayMetrics = context.getResources().getDisplayMetrics();
    float dpWidth = displayMetrics.widthPixels / displayMetrics.density;
    int noOfColumns = (int) (dpWidth / 180);
    return noOfColumns;
}

& change your adapter code to

myTV.setLayoutManager(new GridLayoutManager(getActivity(),calculateNoOfColumns(getActivity())));
Mohamed Mohaideen AH
  • 2,527
  • 1
  • 16
  • 24