我正在片段中使用Recyclerview ... 在片段内部,我通过以下方式设置GridLayout:
myTV.setLayoutManager(new GridLayoutManager(getActivity(),3));
代码说, 横向和纵向模式仅3列 。
但是我希望最大列数以适合用户在旋转手机/平板电脑时使用的屏幕。...
这是我的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>
我使用了 android:numColumns =“ auto_fit” 。 但我没有工作。...
您能告诉我如何解决此问题吗?这是另一个问题...
答案 0 :(得分:2)
Check this for better solution
您可以在此处创建一个用于返回no of columns
的类,也可以直接使用方法。
将此方法添加到片段类。
public int calculateNoOfColumns(Context context) {
DisplayMetrics displayMetrics = context.getResources().getDisplayMetrics();
float dpWidth = displayMetrics.widthPixels / displayMetrics.density;
int noOfColumns = (int) (dpWidth / 180);
return noOfColumns;
}
并将您的适配器代码更改为
myTV.setLayoutManager(new GridLayoutManager(getActivity(),calculateNoOfColumns(getActivity())));