android - 如何在 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。
解决方案
据我所知,如果你想重绘一个视图,你调用 invalidate ,如果你想更新视图边界,你也需要调用 requestLayout 。
推荐阅读
- python - 使用 python 访问 JSON websocket 提要中的单个组件
- kubernetes - kubernetes 和 etcd:无操作,但指标“etcd_server_slow_apply_total”增加到 40
- oracle - 如何修复 ORA-01422:- Fetch 不起作用
- typescript - TypeScript 中作为类型的函数
- javascript - RxJS - 有条件地在管道中添加 observable
- python - 如何识别和标记列/数组中每第 n 个元素的序列中的异常或每五组中的“奇数”
- php - 如何在 WordPress PHP Twilio 中使用彩信回复入站短信
- javascript - recatjs 中的 from 验证不会发生?
- java - 为什么参数中的列表不能向上转换?
- php - 是否可以在 IIS 6.0 上使用 php 7?