进度条的运用还算比较多,比如说我们下载APP时,都会有进度条。不多说,直接上代码。
MainActivity.java
package com.example.progressbartest;
import android.os.Bundle;
import android.os.Handler;
import android.app.Activity;
import android.view.View;
import android.widget.Button;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends Activity {
private Button startButton;
private Button stopButton;
private TextView result;
private ProgressBar MyProgressBar;
private final static int Value=5;
private int i=0;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.progress);
setTitle("ProgressBar");
startButton=(Button)findViewById(R.id.startButton);
stopButton=(Button)findViewById(R.id.stopButton);
result=(TextView)findViewById(R.id.result);
MyProgressBar=(ProgressBar)findViewById(R.id.firstProgressBar);
MyProgressBar.setVisibility(0);//刚开始设置进度条可见
MyProgressBar.setVisibility(View.GONE);//不可见
MyProgressBar.setVisibility(View.VISIBLE);//可见
MyProgressBar.setVisibility(View.INVISIBLE);//不可见
MyProgressBar.setVisibility(View.VISIBLE);//可见
startButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if(i>=MyProgressBar.getMax()){
i=0;
}
result.setText(((double)i/MyProgressBar.getMax()*100)+"%");
handler.post(progressBarThread);
}
});
stopButton.setOnClickListener(new View.OnClickListener()
{
@Override
public void onClick(View v) {
handler.removeCallbacks(progressBarThread);
}
});
}
//创建Handler对象
Handler handler=new Handler();
//创建线程对象
MyRunnable progressBarThread=new MyRunnable();
class MyRunnable implements Runnable{
@Override
public void run() {
i+=Value;
//每隔1秒调用一次progressBarThread线程
handler.postDelayed(progressBarThread, 1000);
MyProgressBar.setProgress(i);
MyProgressBar.setSecondaryProgress(i+Value);
result.setText(((double)i/MyProgressBar.getMax()*100)+"%");
if(i>=MyProgressBar.getMax()){
handler.removeCallbacks(progressBarThread);
test();
}
}
}
public void test(){
Toast.makeText(this, "progressBar is max", 1).show();
}
}
通过创建Handler对象管理线程,完成功能。
上面重复的设置setVisibility,只是为了让自己搞清楚setVisibility的属性值情况。
通过查看源码:
public void setVisibility(int v) {
if (getVisibility() != v) {
super.setVisibility(v);
if (mIndeterminate) {
// let's be nice with the UI thread
if (v == GONE || v == INVISIBLE) {
stopAnimation();
} else {
startAnimation();
}
}
}
}