jsj*_*ics 5 android android-layout
我试图将多个textviews添加到已经膨胀的布局中。显示的信息是从数据库中提取的,为数据库中的每一行都创建了一个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);
}
});
}
Run Code Online (Sandbox Code Playgroud)
此函数成功运行一次,并出现第一个textview。但是,当第二次调用它时,它在display.addView(temp);上失败。符合以下错误:
java.lang.IllegalStateException: The specified child already has a parent. You must call removeView() on the childs's parent first.
Run Code Online (Sandbox Code Playgroud)
我不确定为什么我的textview如果已经被新实例化,为什么已经有一个父级。另外,我使用临时文本视图来绕过我的可运行对象,而无法引用本地文本视图t。它是否正确?任何帮助,将不胜感激。
不要使用成员变量(当然,它可以修改并且不是本地的),而是使用 afinal TextView代替:
final TextView t = new TextView(getBaseContext());
// ...
temp = t; // Remove this
runOnUiThread(new Runnable() {
public void run() {
// ...
display.addView(t);
}
});
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2574 次 |
| 最近记录: |