简体   繁体   中英

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.

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:

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

new Handler()

create a new Runnable and call the postOnUiThread() method of the handler is not very...usefull i guess

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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