首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >Android:后台更新TableLayout

Android:后台更新TableLayout
EN

Stack Overflow用户
提问于 2018-08-07 05:13:47
回答 1查看 33关注 0票数 0

在一个安卓应用程序上工作,我需要一个TableLayout来定期更新,而不会阻塞用户界面线程。下面是TableLayout:

代码语言:javascript
复制
<TableLayout
  android:id="@+id/pidata"
  android:layout_width="wrap_content"
  android:layout_height="match_parent">
</TableLayout>

下面是需要运行的代码的要点,并且每隔几秒钟就用新数据更新TableLayout

代码语言:javascript
复制
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) {
    }
}

以前的代码

代码语言:javascript
复制
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();
EN

回答 1

Stack Overflow用户

发布于 2018-08-07 05:19:45

您不能在UI线程上调用Thread.sleep,因为它将在方法未完成时阻止对屏幕的所有更新,您必须使用以下解决方案之一:

  • 使用带有重发消息的android.os.Handler (handleMessage),它将在UI线程上运行,但将在后台等待新消息的到达;(简单的解决方案)
  • 自己使用线程,并将消息发送到处理程序以返回到UI线程;(最佳解决方案)
  • 使用CountdownTimer (它确实需要固定的时间量才能启动,达到0,停止进程);
  • 使用带有while(true)循环的AsyncTask,使用doInBackground中的publishProgress并在onProgressUpdated处理状态更改以接触UI (不推荐,原因是AsyncTasks的生命周期必须较短);
  • 使用服务执行与AsyncTask相同的操作并将广播发送到活动;(复杂解决方案)
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/51715715

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档