首页 > 解决方案 > 如何在 addView 一些 textview 后使 Android 线性布局刷新?

问题描述

我的 res xml 有一个线性布局和一个按钮

    <LinearLayout
        android:id="@+id/linearLayout"
        android:layout_width="match_parent"
        android:layout_height="48dp"
        android:layout_marginStart="32dp"
        android:layout_marginTop="32dp"
        android:layout_marginEnd="32dp"
        android:gravity="center_horizontal"
        android:orientation="horizontal"

        <TextView
            android:id="@+id/textView"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="TextView" />
    </LinearLayout>

    <Button
        android:id="@+id/btn_add_text"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginBottom="84dp"
        android:text="Button" />

单击按钮一些char数组一一添加到linearLayout中

    val chars = "Hello".toCharArray() 

    btn_add_text.setOnClickListener {
        linearLayout.removeAllViews()
        chars.forEachIndexed { index, char ->
            val tv = Textview(this)
            tv.textSize = 36f
            tv.text = char
            tv.id = index
            linearLayout.addView(tv)
            linearLayout.invalidate()
    }

在 forEachIndexed 循环完成后,linearLayout 被刷新,可以看到 [H][e][l][l][o] 五个文本视图。但我想在每个linearLayout.addView(tv)之后刷新linearLayout。

标签: androidkotlinandroid-linearlayout

解决方案


据我所知,如果你想重绘一个视图,你调用 invalidate ,如果你想更新视图边界,你也需要调用 requestLayout 。


推荐阅读