安卓使用RecyclerView一行显示多条数据

背景

平常使用RecyclerView时,都是一行一行显示数据,但是某些场景下,我们需要一行显示多条数据.

效果图

实现方案

  1. 适配器
class RvAdapter : RecyclerView.Adapter<RecyclerView.ViewHolder>() {
    private var mDataList = mutableListOf<String>()
    private lateinit var mContext: Context
    override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) {
        val data = mDataList[position]
        holder.itemView.imageView.setImageResource(R.mipmap.ic_launcher)
        holder.itemView.setOnClickListener {
            setOnItemClickListener(data)
        }
    }

    fun setData(dataList: List<String>) {
        mDataList.clear()
        mDataList.addAll(dataList)
        notifyDataSetChanged()
    }

    override fun getItemCount(): Int = mDataList.size

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
        mContext = parent.context
        val view = LayoutInflater.from(mContext).inflate(R.layout.item_rv, parent, false)
        return ViewHolder(view)
    }

    private fun setOnItemClickListener(data: String) {
        Toast.makeText(mContext, data, Toast.LENGTH_SHORT).show()
    }

    class ViewHolder(itemView: View?) : RecyclerView.ViewHolder(itemView!!)
}
  1. 适配器布局文件:item_rv.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:orientation="vertical">

    <ImageView
        android:id="@+id/imageView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_margin="10dp"
        android:gravity="center" />

</LinearLayout>
  1. 主界面
class RecyclerViewActivity : AppCompatActivity() {
    private lateinit var adapter: RvAdapter

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_recycler_view)
        initRecyclerView()
        loadData()
    }

    private fun initRecyclerView() {
        adapter = RvAdapter()
        recyclerView.adapter = adapter

        //设置布局类型
        recyclerView.layoutManager = GridLayoutManager(this, 4, GridLayoutManager.VERTICAL, false)
    }

    private fun loadData() {
        val data = ArrayList<String>()
        for (i in 0..50) {
            data.add("text-$i")
        }
        adapter.setData(data)
    }
}
  1. 主界面布局文件:activity_recycler_view.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <androidx.recyclerview.widget.RecyclerView
        android:id="@+id/recyclerView"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_gravity="center" />
</LinearLayout>

完整源代码

https://gitee.com/cxyzy1/recyclerViewDemo/tree/master/recyclerViewDemo/app1

推荐阅读更多精彩内容