Friday 26 September 2014

Progressbar simple example

Your activity_main like this;

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context=".MainActivity" >

    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal"
        android:orientation="horizontal" >
       
        <Button
            android:id="@+id/btn_download"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Download"/>
       
    </LinearLayout>

</LinearLayout>

You MainActivity.java like this;

package com.example.progressbar;

import android.os.Bundle;
import android.os.Handler;
import android.app.Activity;
import android.app.ProgressDialog;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ProgressBar;

public class MainActivity extends Activity {
ProgressDialog pb;
Button btn_download;
int pbstatus;
Handler pbhandler = new Handler();
long filesize = 0;

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

}

private void addListenerOnButton() {
// TODO Auto-generated method stub
btn_download = (Button) findViewById(R.id.btn_download);
btn_download.setOnClickListener(new OnClickListener() {

public void onClick(View v) {
// TODO Auto-generated method stub
pb = new ProgressDialog(v.getContext());
pb.setCancelable(true);
pb.setMessage("File is Downloading...");
pb.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
pb.setMax(100);
pb.setProgress(0);
pb.show();
pbstatus = 0;
filesize = 0;
new Thread(new Runnable() {

@Override
public void run() {
// TODO Auto-generated method stub
while (pbstatus < 100) {
pbstatus = incr();
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
pbhandler.post(new Runnable() {

@Override
public void run() {
// TODO Auto-generated method stub
pb.setProgress(pbstatus);

}
});

}
if (pbstatus >= 100) {
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
pb.dismiss();
}
}

}).start();
}
});
}

private int incr() {
// TODO Auto-generated method stub
while (filesize <= 1000000) {
filesize++;
if (filesize == 100000) {
return 10;
} else if (filesize == 200000) {
return 20;
} else if (filesize == 300000) {
return 30;
}
}
return 100;
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}

}

App like this;




No comments:

Post a Comment