在 Android 中从 Thread 更新 UI [英] Update UI from Thread in Android

查看:27
本文介绍了在 Android 中从 Thread 更新 UI的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想从更新进度条的线程更新我的 UI.不幸的是,当从runnable"更新进度条的 drawable 时,进度条消失了!在另一边的 onCreate() 中更改进度条的 drawable 是可行的!

I want to update my UI from a Thread which updates a Progressbar. Unfortunately, when updating the progressbar's drawable from the "runnable" the progressbar disappears! Changing the progressbars's drawable in onCreate() on the otherside works!

有什么建议吗?

public void onCreate(Bundle savedInstanceState) {
    res = getResources();
    super.onCreate(savedInstanceState);
    setContentView(R.layout.gameone);
    pB.setProgressDrawable(getResources().getDrawable(R.drawable.green)); //**Works**/
    handler.postDelayed(runnable, 1);       
}

private Runnable runnable = new Runnable() {
    public void run() {  
        runOnUiThread(new Runnable() { 
            public void run() 
            { 
                //* The Complete ProgressBar does not appear**/                         
                pB.setProgressDrawable(getResources().getDrawable(R.drawable.green)); 
            } 
        }); 
    }
}

推荐答案

你应该在 AsyncTask(智能后台线程)和 ProgressDialog

You should do this with the help of AsyncTask (an intelligent backround thread) and ProgressDialog

AsyncTask 支持正确且轻松地使用 UI 线程.此类允许在 UI 线程上执行后台操作并发布结果,而无需操作线程和/或处理程序.

AsyncTask enables proper and easy use of the UI thread. This class allows to perform background operations and publish results on the UI thread without having to manipulate threads and/or handlers.

异步任务由在后台线程上运行的计算定义,其结果发布在 UI 线程上.一个异步任务由 3 个通用类型定义,称为 Params、Progress 和 Result,以及 4 个步骤,称为 begin、doInBackground、processProgress 和 end.

An asynchronous task is defined by a computation that runs on a background thread and whose result is published on the UI thread. An asynchronous task is defined by 3 generic types, called Params, Progress and Result, and 4 steps, called begin, doInBackground, processProgress and end.

四个步骤

当一个异步任务被执行时,任务会经历4个步骤:

When an asynchronous task is executed, the task goes through 4 steps:

onPreExecute(),在任务执行后立即在 UI 线程上调用.此步骤通常用于设置任务,例如通过在用户界面中显示进度条.

onPreExecute(), invoked on the UI thread immediately after the task is executed. This step is normally used to setup the task, for instance by showing a progress bar in the user interface.

doInBackground(Params...),在 onPreExecute() 执行完毕后立即在后台线程上调用.此步骤用于执行可能需要很长时间的后台计算.异步任务的参数传递到这一步.计算的结果必须由这一步返回,并传回上一步.这一步也可以使用publishProgress(Progress...)来发布一个或多个进度单元.这些值发布在 UI 线程的 onProgressUpdate(Progress...) 步骤中.

doInBackground(Params...), invoked on the background thread immediately after onPreExecute() finishes executing. This step is used to perform background computation that can take a long time. The parameters of the asynchronous task are passed to this step. The result of the computation must be returned by this step and will be passed back to the last step. This step can also use publishProgress(Progress...) to publish one or more units of progress. These values are published on the UI thread, in the onProgressUpdate(Progress...) step.

onProgressUpdate(Progress...),在调用 publishProgress(Progress...) 后在 UI 线程上调用.执行的时间是不确定的.此方法用于在后台计算仍在执行时在用户界面中显示任何形式的进度.例如,它可用于为进度条设置动画或在文本字段中显示日志.

onProgressUpdate(Progress...), invoked on the UI thread after a call to publishProgress(Progress...). The timing of the execution is undefined. This method is used to display any form of progress in the user interface while the background computation is still executing. For instance, it can be used to animate a progress bar or show logs in a text field.

onPostExecute(Result),在后台计算完成后在 UI 线程上调用.后台计算的结果作为参数传递给这一步.线程规则

onPostExecute(Result), invoked on the UI thread after the background computation finishes. The result of the background computation is passed to this step as a parameter. Threading rules

要使此类正常工作,必须遵循一些线程规则:

任务实例必须在 UI 线程上创建.execute(Params...) 必须在 UI 线程上调用.不要手动调用 onPreExecute()、onPostExecute(Result)、doInBackground(Params...)、onProgressUpdate(Progress...).该任务只能执行一次(如果尝试第二次执行将引发异常.)

The task instance must be created on the UI thread. execute(Params...) must be invoked on the UI thread. Do not call onPreExecute(), onPostExecute(Result), doInBackground(Params...), onProgressUpdate(Progress...) manually. The task can be executed only once (an exception will be thrown if a second execution is attempted.)

示例代码
在这个例子中适配器做了什么并不重要,更重要的是理解你需要使用 AsyncTask 来显示进度对话框.

Example code
What the adapter does in this example is not important, more important to understand that you need to use AsyncTask to display a dialog for the progress.

private class PrepareAdapter1 extends AsyncTask<Void,Void,ContactsListCursorAdapter > {
    ProgressDialog dialog;
    @Override
    protected void onPreExecute() {
        dialog = new ProgressDialog(viewContacts.this);
        dialog.setMessage(getString(R.string.please_wait_while_loading));
        dialog.setIndeterminate(true);
        dialog.setCancelable(false);
        dialog.show();
    }
    /* (non-Javadoc)
     * @see android.os.AsyncTask#doInBackground(Params[])
     */
    @Override
    protected ContactsListCursorAdapter doInBackground(Void... params) {
        cur1 = objItem.getContacts();
        startManagingCursor(cur1);

        adapter1 = new ContactsListCursorAdapter (viewContacts.this,
                R.layout.contact_for_listitem, cur1, new String[] {}, new int[] {});

        return adapter1;
    }

    protected void onPostExecute(ContactsListCursorAdapter result) {
        list.setAdapter(result);
        dialog.dismiss();
    }
}

这篇关于在 Android 中从 Thread 更新 UI的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆