vijay
5/29/2015 - 7:35 AM

ProgressBar using Handlar

ProgressBar using Handlar

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <ProgressBar
        android:id="@+id/progressBar"
        style="?android:attr/progressBarStyleHorizontal"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"
        android:indeterminate="false"
        android:max="100"
        android:progress="0" />

</RelativeLayout>
public class MainActivity extends Activity {

    ProgressBar progressBar;
    Thread thread;
    Handler handler;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.handler_test);

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


        handler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                super.handleMessage(msg);

                progressBar.setProgress(msg.arg1);
            }
        };


        thread = new Thread(new MyThread());

        thread.start();

    }

    class MyThread implements Runnable {
        @Override
        public void run() {

            for (int i = 0; i < 100; i++) {

                Message message = Message.obtain();
                message.arg1 = i;
                handler.sendMessage(message);
                try {
                    Thread.sleep(100);
                } catch (Exception e) {

                }


            }
        }
    }
}