简体   繁体   English

如何在 addView 一些 textview 后使 Android linearlayout 刷新?

[英]How can I make Android linearlayout refresh after addView some textview?

My res xml has a linearlayout and a button我的资源 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" />

click the button some char array added to linearLayout one by one点击按钮将一些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()
    }

After forEachIndexed loop has finished linearLayout refreshed and can see [H][e][l][l][o] five textviews. forEachIndexed 循环完成后,linearLayout 刷新,可以看到 [H][e][l][l][o] 五个文本视图。 But I want to make linearLayout refresh after each linearLayout.addView(tv).但是我想在每次 linearLayout.addView(tv) 之后刷新 linearLayout。

As far as I know if you want a view to redraw you call invalidate and if you want to update the viewbounds you need to call requestLayout as well.据我所知,如果你想重绘视图,你可以调用 invalidate,如果你想更新视图边界,你也需要调用 requestLayout。

If you want to see step by step you can try this:如果你想一步一步看,你可以试试这个:

val handler = Handler()
btn_add_text.setOnClickListener {
linearLayout.removeAllViews()
chars.forEachIndexed { index, char ->
      val tv = TextView(context!!)
      tv.textSize = 24f
      tv.text = char.toString()
      tv.id = index
      handler.postDelayed(Runnable {
          linearLayout.addView(tv)
      },500 * index.toLong())
    }
}

I think linearlayout is refreshing so fast, you are not able to see intermediate refreshes, what you can do is, use a worker thread and make it sleep for 500 ms between each iteration, and post data to main thread via handler, your each change of charachter will be visible.我认为 linearlayout 刷新得如此之快,您看不到中间刷新,您可以做的是,使用工作线程并使其在每次迭代之间休眠 500 毫秒,并通过处理程序将数据发布到主线程,您的每次更改字符将是可见的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM