如何使用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<View>(R.id.recycleView)
确保你初始化如下
var recyclerView = findViewById<View>(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)
- 匕首2与Kotlin的多重绑定
- UnsupportedOperationException“android”命令不再包含在SDK中
- java.lang.NoClassDefFoundError:com.example.api.retrofit.AuthenticationInterceptor $ intercept $ 1
- 在Android上重复注释
- 如何从歌曲URI获取唱片集ID
- 如何在Kotlin中设置回调?
- 调用File.createNewFile()时,权限被拒绝 Android的
- 从gradle运行HelloAndroid?
- 使用“kotlin-kapt”插件,Android Studio不提供有关Dagger 2的具体错误