从Android中的线程更新UI [英] Update UI from Thread in Android

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

问题描述

我想从一个更新进度条的线程更新我的UI.不幸的是,从可运行"更新进度条的可绘制对象时,进度条会消失!在另一端的 onCreate()中更改进度条的可绘制对象!

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)); 
            } 
        }); 
    }
}

推荐答案

您应该在 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个步骤

执行异步任务时,该任务将经历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 ...)发布一个或多个进度单位.这些值在onProgressUpdate(Progress ...)步骤中发布在UI线程上.

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线程上创建任务实例.必须在UI线程上调用execute(Params ...).不要手动调用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中的线程更新UI的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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