📅  最后修改于: 2023-12-03 15:32:31.430000             🧑  作者: Mango
ScrollView是Android中经常使用的控件之一,它允许用户在视图中滚动以查看更多内容。在这篇文章中,我们将讨论使用Kotlin编写Dynamic Horizontal ScrollView的实现方法。
<HorizontalScrollView
android:id="@+id/horizontalScrollView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:scrollbars="none">
<LinearLayout
android:id="@+id/linearLayout"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:orientation="horizontal" />
</HorizontalScrollView>
val layout = findViewById<LinearLayout>(R.id.linearLayout)
// 添加子项
for (i in 0 until 10) {
val textView = TextView(this)
textView.text = "Item $i"
textView.setPadding(16, 16, 16, 16)
layout.addView(textView)
}
val layoutParams = LinearLayout.LayoutParams(
LinearLayout.LayoutParams.WRAP_CONTENT,
LinearLayout.LayoutParams.MATCH_PARENT
)
val layout = findViewById<LinearLayout>(R.id.linearLayout)
// 添加子项
for (i in 0 until 10) {
val textView = TextView(this)
textView.text = "Item $i"
textView.setPadding(16, 16, 16, 16)
textView.layoutParams = layoutParams // 设置布局参数
layout.addView(textView)
}
// 启用滚动条
horizontalScrollView.isHorizontalScrollBarEnabled = true
horizontalScrollView.setOnScrollChangeListener { _, _, _, _, _ ->
// 滚动时的操作
}
下面是一个完整的示例代码:
<HorizontalScrollView
android:id="@+id/horizontalScrollView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:scrollbars="none">
<LinearLayout
android:id="@+id/linearLayout"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:orientation="horizontal" />
</HorizontalScrollView>
val layoutParams = LinearLayout.LayoutParams(
LinearLayout.LayoutParams.WRAP_CONTENT,
LinearLayout.LayoutParams.MATCH_PARENT
)
val layout = findViewById<LinearLayout>(R.id.linearLayout)
// 添加子项
for (i in 0 until 10) {
val textView = TextView(this)
textView.text = "Item $i"
textView.setPadding(16, 16, 16, 16)
textView.layoutParams = layoutParams // 设置布局参数
layout.addView(textView)
}
// 启用滚动条
horizontalScrollView.isHorizontalScrollBarEnabled = true
// 滚动事件监听器
horizontalScrollView.setOnScrollChangeListener { _, _, _, _, _ ->
// 滚动时的操作
}