如何使用AsyncTask更新UI

时间:2011-05-19 10:25:40

标签: android android-asynctask

我想在特定时间间隔内用一些数据信息更新UI,那么任何人都可以帮助我使用AsyncTask吗?

2 个答案:

答案 0 :(得分:1)

使用AsyncTask的onProgressUpdate()方法。它在UI线程上执行。

答案 1 :(得分:0)

尝试Asynctask,如下所示:

try{
    class test extends AsyncTask{


         TextView tv_per;
         int mprogress;

        Dialog UpdateDialog = new Dialog(ClassContext);

        @Override
        protected void onPreExecute() {
            // TODO Auto-generated method stub
            mprogress = 0;

            UpdateDialog.setTitle(getResources().getString(R.string.app_name));
            UpdateDialog.setContentView(R.layout.horizontalprogressdialog);
            TextView dialog_message =  (TextView)UpdateDialog.findViewById(R.id.titleTvLeft);
            tv_per = (TextView)UpdateDialog.findViewById(R.id.hpd_tv_percentage);
            dialog_message.setText(getResources().getString(R.string.dialog_retrieving_data));
            dialog_message.setGravity(Gravity.RIGHT);
            UpdateDialog.setCancelable(false);
            UpdateDialog.show();
            super.onPreExecute();
        }



        @Override
        protected void onProgressUpdate(Object... values) {
            // TODO Auto-generated method stub
            ProgressBar update = (ProgressBar)UpdateDialog.findViewById(R.id.horizontalProgressBar);
            update.setProgress((Integer) values[0]);
            int percent =  (Integer) values[0];
            if(percent>=100)
            {
                percent=100;
            }
            tv_per = (TextView)UpdateDialog.findViewById(R.id.hpd_tv_percentage);
             tv_per.setText(""+percent);
        }



        @Override
        protected Object doInBackground(Object... params) {
            // TODO Auto-generated method stub
            //your code of UI operation
}

            super.onPostExecute(result);
            UpdateDialog.dismiss();
        }

     }
     new test().execute(null);

 }
 catch(Exception e)
 {
     e.printStackTrace();
 }

另请参阅此链接: Fetch data from server and refresh UI when data is fetched?