如何使用kotlin将layoutmanager设置为RecycleView

我如何设置layoutmanager到RecycleView使用kotlin作为java代码如下:

mRecyclerView.setLayoutManager(mLinearLayoutManager); 

您可以使用Kotlin的综合属性

 mRecyclerView.layoutManager = LinearLayoutManager(context) 

LinearLayoutManager构造函数

为了做到这一点,添加到您的根级build.gradle文件如下:

 buildscript { dependencies { classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlinVersion" } } 

然后在你的应用程序的build.gradle的顶部添加以下内容:

apply plugin: 'kotlin-android-extensions'

只需写这个来设置LayoutManager

  // Define this globally lateinit var recyclerView: RecyclerView // Initialize this after `activity` or `fragment` is created recyclerView = findViewById(R.id.recyclerView) as RecyclerView recyclerView.setHasFixedSize(true) recyclerView.layoutManager = LinearLayoutManager(activity!!) as RecyclerView.LayoutManager 

你可以这样做

 val linearLayoutManager = LinearLayoutManager(this) linearLayoutManager.orientation = LinearLayoutManager.VERTICAL recyclerview!!.layoutManager = linearLayoutManager recyclerview!!.isNestedScrollingEnabled = true recyclerview!!.setHasFixedSize(true) 

我有同样的问题,原因是我已经初始化recyclerView为

 var recyclerView = findViewById(R.id.recycleView) 

确保你初始化如下

 var recyclerView = findViewById(R.id.recycleView) as RecyclerView 

在您的应用程序构建中应用插件

  apply plugin: 'kotlin-android-extensions' 

对于我的RecyclerView案例视图ID是my_recycler_view

在你的java文件中写入 –

 my_recycler_view.layoutManager = LinearLayoutManager(context) 

默认情况下, LinearLayoutManager(context)将设置垂直方向,根据需要进行更新。

您可以使用此代码设置:

 binding.recyclerView.setHasFixedSize(true) binding.recyclerView.layoutManager = LinearLayoutManager(this ,LinearLayoutManager.VERTICAL ,false) binding.recyclerView.adapter = customAdapter(this ,getList()) 

recyclerView.layoutManager = LinearLayoutManager(context)

要么

recyclerView.layoutManager = GridLayoutManager(context, spanCount)