简体   繁体   中英

Recycler View Horizontal Scroll with 2 columns

Here is I have I have tried so far

LinearLayoutManager layoutManager =
        new GridLayoutManager(getActivity(), 2, GridLayoutManager.HORIZONTAL, false);

but It showed 2 rows instead of two columns.

How can I show two items with horizontal scroll with recycler view?

Alright here is a funda,

When you are using GridLayoutManager.HORIZONTAL , second parameter will be considered as number of rows

while, when you write GridLayoutManager.VERTICAL second parameter will be considered as number of columns

Also, this

LinearLayoutManager layoutManager =
        new GridLayoutManager(getActivity(), 2, GridLayoutManager.HORIZONTAL, false);

supposed to be,

GridLayoutManager layoutManager =
            new GridLayoutManager(getActivity(), 2, GridLayoutManager.HORIZONTAL, false);

in above code, 2 is considered as number of rows to be generated.

To achieve what you need you need to combine two things: setup GridLayoutManager and set up adapter:

in Fragment/Activity:

 val snapHelper = PagerSnapHelper()
        snapHelper.attachToRecyclerView(recyclerView)

//Grid layout, 2 columns
        recyclerView.layoutManager =
            GridLayoutManager(this.context, 2, RecyclerView.HORIZONTAL, false)

and then in your adapter:

var displayMetrics = DisplayMetrics()
private var screenWidth = 0

in onCreateViewHolder:

(parent.context as MainActivity).windowManager.defaultDisplay.getMetrics(displayMetrics)
    screenWidth = displayMetrics.widthPixels

in onBindViewHolder:

    val itemPadding = 8

    //here you may change the divide amount from 2.5 to whatever you need 
    val itemWidth = (screenWidth - itemPadding).div(2.5)

    val layoutParams = holder.itemView.layoutParams
    layoutParams.height = layoutParams.height
    layoutParams.width = itemWidth.toInt()
    holder.itemView.layoutParams = layoutParams

Recently faced the same problem, ended with creating a custom GridLayoutManager that allowed me to fix the row count and column count together.

Link : - https://gist.github.com/KaveriKR/04bfef5ffc9c00a8b6fca503da497322

This custom layout manger makes use of the generateDefaultLayoutParams and two other functions to set different layout params for the layout manger.

try below code

RecyclerView.LayoutManager mLayoutManager = new GridLayoutManager(this, 2);
    recyclerView.setLayoutManager(mLayoutManager);

All answers at Java but if someone searches for Kotlin;

val layoutManager = GridLayoutManager(requireContext(),  2)

    recyclerViewSymbol.layoutManager = symbolLayoutManager
RecyclerView.LayoutManager mLayoutManager = new GridLayoutManager(activity,2,LinearLayoutManager.HORIZONTAL,false);
recyclerView.setLayoutManager(mLayoutManager);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM