在一个安卓应用程序上工作,我需要一个TableLayout来定期更新,而不会阻塞用户界面线程。下面是TableLayout:
<TableLayout
android:id="@+id/pidata"
android:layout_width="wrap_content"
android:layout_height="match_parent">
</TableLayout>
下面是需要运行的代码的要点,并且每隔几秒钟就用新数据更新TableLayout
。
public static TableLayout piTableLayout;
public static HashSet<PIModel> PiData;
piTableLayout = (TableLayout)findViewById(R.id.pidata);
while (isRunning) {
PiData = getPiData();
piTableLayout.removeAllViews();
for (PIModel model : PiData) {
TableRow row = new TableRow(this);
TableRow.LayoutParams rowParams = new TableRow.LayoutParams();
rowParams.setMargins(0, -4, 0, -4);
rowParams.height = 40;
TextView pointNameText = new TextView(this);
pointNameText.setText(model.getAttributeName());
pointNameText.setGravity(Gravity.LEFT);
pointNameText.setLayoutParams(rowParams);
pointNameText.setTextColor(Color.parseColor("white"));
pointNameText.setTypeface(null, Typeface.BOLD);
pointNameText.setPadding(0, 0, 10, 0);
TextView valueText = new TextView(this);
valueText.setText(model.getValue());
valueText.setLayoutParams(rowParams);
valueText.setTextColor(Color.parseColor("white"));
valueText.setPadding(0, 0, 10, 0);
piTableLayout.addView(row);
row.addView(pointNameText);
row.addView(valueText);
}
try {
Thread.sleep(3000);
}
catch (InterruptedException ex) {
}
}
以前的代码
Handler piHandler = new Handler();
Runnable piRunnable = new Runnable() {
@Override
public void run() {
while (isRunning) {
piHandler.post(new Runnable() {
@Override
public void run() {
//logic to add to TableLayout
}
});
try {
Thread.sleep(3000);
}
catch (InterruptedException ex) {
}
}
}
};
new Thread(piRunnable).start();
发布于 2018-08-07 05:19:45
您不能在UI线程上调用Thread.sleep,因为它将在方法未完成时阻止对屏幕的所有更新,您必须使用以下解决方案之一:
https://stackoverflow.com/questions/51715715
复制相似问题