简体   繁体   English

如何添加控件以在Android的工作线程中查看

[英]How to add controls to view in a worker thread in Android

I need to create several UI controls in an android application at runtime. 我需要在运行时在android应用程序中创建几个UI控件。

In order to not freeze the UI while creating controls (and to show a "Loading..." box), I want to use a worker thread like this: 为了在创建控件时不冻结UI(并显示“正在加载...”框),我想使用如下工作线程:

private class LoadControls extends AsyncTask<TdcItem, Integer, Integer> {
    private ProgressDialog dialog;

    @Override
    protected void onPreExecute() {
        dialog = new ProgressDialog(FormActivity.this);
        dialog.setMessage(getString(R.string.loading_message));
        dialog.setIndeterminate(true);
        dialog.setCancelable(false);
        dialog.show();
    }

    protected Integer doInBackground(TdcItem... items) {
        ScrollView accordion = (ScrollView) findViewById(R.id.accordion);
        int count = items.length;
        for (int i = 0; i < count; i++) {
            Button header = new Button(FormActivity.this);
            header.setText(items[i].getName());
            if (isCancelled()) break;
        }

        return count;
    }

    protected void onPostExecute(Integer result) {
        dialog.dismiss();
    }
}

This code in part of the Activity which will response to button clicks. 此代码是“活动”的一部分,将响应按钮的单击。

The problem is that compiler says that I cannot create a button in a worker thread. 问题是编译器说我无法在工作线程中创建按钮。 How can I do it? 我该怎么做?

it seems to be a UI stuff you want to do so it should be done on UI thread... otherwise you ll have to create a 它似乎是您想要做的一个UI东西,因此应该在UI线程上完成...否则,您将不得不创建一个

new Handler()

create a new Runnable and call the postOnUiThread() method of the handler is not very...usefull i guess 创建一个新的Runnable并调用该处理程序的postOnUiThread()方法不是非常... usefull我猜

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM