我有一个EditText和一个TextView,我想在每次迭代中更新我的TextView(ConsoleWindow在循环中运行;它从一个处理程序调用,因此在UIthread上运行)。
问题是我的TextView仅在第一轮中更新,然后它保留了运行时其余部分的第一个条目(尽管每一轮中dataString
是不同的一个):
private void ConsoleWindow(String dataString) {
LinearLayout layout = new LinearLayout(getApplicationContext());
if (first2) { //first2 is true when application is launched
// ONLY SET LAYOUT AND EDITTEXT IN FIRST RUN TO SAVE CAPACITY
// LINEAR LAYOUT
setContentView(layout);
layout.setOrientation(LinearLayout.VERTICAL);
layout.setBackgroundColor(Color.parseColor("#000000")); // black
// EDITTEXT
EditText et = new EditText(getApplicationContext());
et.setHint("Enter Command");
layout.addView(et);
first2 = false;
}
// TEXTVIEW
TextView tv = new TextView(getApplicationContext());
tv.setText(dataString); // KEEPS THE SAME UNTIL THE 1ST ROUND
layout.addView(tv);
}
我已经尝试过tv.invalidate()和tv.postInvalidate(),但这并没有效果。有人可以帮帮我吗?
答案 0 :(得分:1)
当first2
为false
时,您只需创建一个新的 LinearLayout layout
,然后在不夸大layout
的情况下直接添加 TextView tv
到layout
。这就是 Textvie w不可见的原因。
private void ConsoleWindow(String dataString) {
LinearLayout layout;
TextView tv;
EditText et;
if (first2) {
layout = new LinearLayout(getApplicationContext());
setContentView(layout);
layout.setOrientation(LinearLayout.VERTICAL);
layout.setBackgroundColor(Color.parseColor("#000000"));
// EDITTEXT
et = new EditText(getApplicationContext());
et.setHint("Enter Command");
layout.addView(et);
tv = new TextView(getApplicationContext());
layout.addView(tv);
first2 = false;
}
if(tv != null) {
tv.setText(dataString);
}
}
答案 1 :(得分:1)
将tv设为全局变量。
private TextView tv;
在此之后,在你的“onCreate()”方法中:
tv = new TextView(getApplicationContext());
然后:
private void ConsoleWindow(String dataString) {
LinearLayout layout = new LinearLayout(getApplicationContext());
if (first2) { //first2 is true when application is launched
// ONLY SET LAYOUT AND EDITTEXT IN FIRST RUN TO SAVE CAPACITY
// LINEAR LAYOUT
setContentView(layout);
layout.setOrientation(LinearLayout.VERTICAL);
layout.setBackgroundColor(Color.parseColor("#000000")); // black
// EDITTEXT
EditText et = new EditText(getApplicationContext());
et.setHint("Enter Command");
layout.addView(et);
first2 = false;
}
// TEXTVIEW
tv.setText(dataString); // KEEPS THE SAME UNTIL THE 1ST ROUND
layout.addView(tv);
}
如果dataString有一些文本,请验证,如下所示
Log.d(TAG , "dataString: " + dataString + "with first time? " + first2.toString());
尝试传递给setContentView(布局);在if语句之外。因为我无法理解为什么你需要这个。
LinearLayout layout = new LinearLayout(getApplicationContext());
setContentView(layout);