在Android 应用开发中,ProgressBar (运行进度条)是较常用到得组件,Android 提供了两种样式来分别表示不同状态下显示得进度条,分别为:圆形进度条是条形进度条。
默认进度条是圆形,可以通过Style 属性来指定系统进度条的大小:
大圆形进度条:
style="?android:attr/progressBarStyleLarge"
大圆形进度条:
style="?android:attr/progressBarStyleSmall"
长条形进度条:
style="?android:attr/progressBarStyleHorizontal"
以下是实例,实现长条进度条功能。
1.以下为xml布局文件主要代码
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="条形进度条"/>
<ProgressBar
android:layout_width="match_parent"
android:layout_height="wrap_content"
style="?android:attr/progressBarStyleHorizontal"
android:max="100"
android:id="@+id/progressBar"
android:progress="50"
android:secondaryProgress="70"
/>
<Button
android:layout_width="wrap_content"
android:gravity="center"
android:text="点击刷新"
android:id="@+id/button"
android:layout_height="wrap_content"
/>
2.以下为 java 逻辑代码:
package com.example.kedongyu.progressbar;
import android.os.Handler;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ProgressBar;
public class MainActivity extends AppCompatActivity implements Runnable {
private Handler handler=new Handler();
private android.widget.ProgressBar pb;
private boolean b;
private Button button;
ProgressBar p;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
pb=(android.widget.ProgressBar)findViewById(R.id.progressBar);
button=(Button)findViewById(R.id.button);
p=new ProgressBar(pb);
new Thread(this).start();
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
new Thread(MainActivity.this).start();
}
});
int current=pb.getProgress(); //当前进度条
int currentMax=pb.getMax(); //最大进度条
int secCurrent=pb.getSecondaryProgress(); //底层进度条
}
@Override
public void run(){
p.run();
}
class ProgressBar{
public android.widget.ProgressBar pb;
public boolean state;
public ProgressBar(android.widget.ProgressBar p){
pb=p;
state=false;
}
public void run(){
if(state)
{
}
else{
state=true;
ProgressBar();
state=false;
}
}
public void ProgressBar(){
int current=0;
int secCurrent=20;
pb.setProgress(current);
pb.setSecondaryProgress(secCurrent);
b=false;
while(true){
if(b==false)
{
if(current>=100){
b=true;
}
else{
pb.setProgress(current++);
pb.setSecondaryProgress(secCurrent++);
}
}
else {
break;
}
try{
Thread.sleep(50);
}
catch (InterruptedException ie)
{
ie.printStackTrace();
Log.v("error","线程错误!");
}
}
}
}
}