Progressbar无法使用处理程序

时间:2016-05-20 11:11:23

标签: android

我创建了一个进度条,我希望进度条运行到80但我的进度条没有响应我不知道问题是什么,我使用处理程序和线程来运行rogressbar

这是我的代码:

 progressbar = (ProgressBar) findViewById(R.id.progressBar);



        final Thread thread = new Thread(new Runnable() {
            @Override
            public void run() {


                for(int i = 0; i<=80; i++){
                    try {
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                        Message message = new Message();
                        message.arg1 = i;
                        handler.sendMessage(message);
                    }
                }

            }
        });
        thread.run();
            handler = new Handler(){
                @Override
                public void handleMessage(Message msg) {
                    super.handleMessage(msg);
                    int value = msg.arg1;

                    progressbar.setProgress(value);

                }
            };



    }


<RelativeLayout
    android:id="@+id/relative"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:gravity="center"
    xmlns:android="http://schemas.android.com/apk/res/android">
    <ProgressBar

    android:layout_width="match_parent"
    android:layout_height="wrap_content"
        android:id="@+id/progressBar"

    style="?android:attr/progressBarStyleHorizontal"
        android:max="100"
    xmlns:android="http://schemas.android.com/apk/res/android" />
    </RelativeLayout>

1 个答案:

答案 0 :(得分:0)

MainActivity.this.runOnUiThread(new Runnable(){
   public void run(){
      for(int i = 0; i<=80; i++){
                try {
                    Thread.sleep(1000);
                    progressbar.setProgress(i);
                } catch (InterruptedException e) {
                    e.printStackTrace();

                }
            }
   }
});