Android RecycleView实现横向,纵向都可滑动的列表

问题

1.RecycleView默认是纵向滑动的,可以通过setOrientation(LinearLayoutManager.HORIZONTAL)设置为横向滑动。

       //指定列表布局方式,默认是纵向垂直
       recycleView.setLayoutManager(new LinearLayoutManager(this));
       //指定列表线性布局,横向水平
        LinearLayoutManager lm = new LinearLayoutManager(this);
        lm.setOrientation(LinearLayoutManager.HORIZONTAL);
        hView.setLayoutManager(lm);
  1. 哪怎么实现实现横向,纵向都可滑动的列表呢?
    答案:HorizontalScrollView+RecyclerView嵌套。效果如下:

《Android RecycleView实现横向,纵向都可滑动的列表》

代码

MainActivity.kt

class MainActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        rv.layoutManager = LinearLayoutManager(this)
        val numbers = arrayListOf<String>("one", "two", "three", "four", "one", "two", "three", "four", "one", "two", "three", "four", "one", "two", "three", "four", "one", "two", "three", "four")
        var adapter = Adapter(this, numbers)
        rv.adapter = adapter
    }


}

class Adapter : RecyclerView.Adapter<RecyclerView.ViewHolder> {
    private var context: Context? = null
    private var list: ArrayList<String>? = null

    constructor(context: Context, list: ArrayList<String>) {
        this.context = context
        this.list = list
    }

    override fun onCreateViewHolder(p0: ViewGroup, p1: Int): RecyclerView.ViewHolder {
        val view: View = LayoutInflater.from(context).inflate(R.layout.list, p0, false)
        return ViewHolder(view)
    }

    override fun getItemCount(): Int {
        return list!!.size
    }

    override fun onBindViewHolder(holder: RecyclerView.ViewHolder, pos: Int) {

    }


    class ViewHolder : RecyclerView.ViewHolder {
        constructor(view: View) : super(view)
    }

}

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".MainActivity">

	<HorizontalScrollView android:layout_width="match_parent" android:scrollbars="none" android:layout_height="wrap_content">

		<android.support.v7.widget.RecyclerView android:id="@+id/rv" android:layout_width="wrap_content" android:layout_height="wrap_content" />
	</HorizontalScrollView>

</LinearLayout>
    原文作者:DeMonnnnnn
    原文地址: https://blog.csdn.net/demonliuhui/article/details/91438066
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞