gpt4 book ai didi

android - 从后台线程添加 View

转载 作者:塔克拉玛干 更新时间:2023-11-02 22:57:25 26 4
gpt4 key购买 nike

我正在尝试将多个 TextView 添加到已经膨胀的布局中。显示的信息是从数据库中提取的,为数据库中的每一行创建一个 TextView 。由于数据库可能非常大,我在后台线程中一次创建一个 TextView ,然后将其添加到前台。

这里是在后台线程调用更新前台的函数:

private TextView temp;
private void addClickableEvent(ReviewHistoryEvent e){
if(e == null){
Log.e(tag,"Attempted to add a null event to review history");
return;
}
TextView t = new TextView(getBaseContext());
t.setTag(e);
t.setText(e.getTime()+" "+e.getEvent());
t.setClickable(true);
t.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT));
t.setTextAppearance(getBaseContext(), R.style.Information_RegularText);
t.setGravity(Gravity.CENTER);
t.setOnClickListener(this);

temp = t;
runOnUiThread(new Runnable() {
public void run() {
LinearLayout display = (LinearLayout) findViewById(R.id.reviewHistory_display);
display.addView(temp);
}
});
}

该函数运行一次成功,出现第一个textview。然而,当它被第二次调用时,它在 display.addView(temp) 上失败了;符合以下错误:

java.lang.IllegalStateException: The specified child already has a parent. You must call removeView() on the childs's parent first.

我不确定为什么我的 textview 已经有了父级,如果它应该是新实例化的话。此外,我使用临时 textview 来绕过我的 runnable 无法引用本地 textview t。这个对吗?任何帮助将不胜感激。

最佳答案

不使用成员变量(当然可以修改并且不是本地的),而是使用 final TextView:

final TextView t = new TextView(getBaseContext());
// ...

temp = t; // Remove this
runOnUiThread(new Runnable() {
public void run() {
// ...
display.addView(t);
}
});

关于android - 从后台线程添加 View ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14841365/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com