简体   繁体   中英

How to update UI using AsyncTask

我想在特定间隔内用一些数据信息更新UI,所以有人可以使用AsyncTask来帮助我吗?

use onProgressUpdate() method of AsyncTask. It is performed on UI thread.

Try Asynctask as shown here:

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

Also refer to this link: Fetch data from server and refresh UI when data is fetched?

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