首页 > 解决方案 > 如何在 kotlin 中制作 ScrollView

问题描述

如何制作一个在代码中动态添加 TextViews 的 ScrollView?现在我有:

<?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:id="@+id/root_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:padding="16dp"
>
<Button
    android:id="@+id/button"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Create TextView"
    />

<ScrollView
    android:id="@+id/Scroll"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical" />
</ScrollView>

作为布局文件,这是我的 kotlin 文件:

class Abfahrtsmonitor : AppCompatActivity(){
override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.abfahrtsmonitor)

    // Variable for counting text view
    var counter: Int = 1;

    // Set a click listener for button widget
    button.setOnClickListener{
        // Create a new TextView instance programmatically
        val text_view: TextView = TextView(this)

        // Creating a LinearLayout.LayoutParams object for text view
        var params : LayoutParams = LayoutParams(
                LayoutParams.MATCH_PARENT, // This will define text         view width
                LayoutParams.WRAP_CONTENT // This will define text view     height
        )
 // Display some text on the newly created text view
        text_view.text = "Hi, i am a TextView. Number : $counter"
 // Finally, add the text view to the view group
        Scroll.addView(text_view)

        // Increment the counter
        counter++

但现在我得到了错误:

java.lang.IllegalStateException:ScrollView 只能承载一个直接子级

标签: androidkotlinscrollview

解决方案


java.lang.IllegalStateException:ScrollView只能托管一个直接子级

ScrollView只能容纳一个孩子,这意味着它只能容纳一个视图,因为它是直接孩子,所以,这样的事情会有所帮助:

<ScrollView
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/root_layout"
    android:layout_width="match_parent"
    android:layout_height="wrap_content">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical">

    // Content in here ...
    </LinearLayout>
</ScrollView>

但是,情况并非如此,因为您已经LinearLayout在布局的根目录中,所以您可能想考虑将其ScrollView作为根目录并将内容放在LinearLayout. http://developer.android.com/reference/android/widget/ScrollView.html


推荐阅读