Android ProgressBar进度条使用详解

2019-12-10 19:07:55丽君

ProgressBar进度条,分为旋转进度条和水平进度条,进度条的样式根据需要自定义,之前一直不明白进度条如何在实际项目中使用,网上演示进度条的案例大多都是通过Button点击增加、减少进度值,使用方法incrementProgressBy(int),最简单的做法是在xml布局文件中放置ProgressBar空间,然后再MainActivity中触发事件后执行incrementProgressBy(int),代码如下:

<LinearLayout xmlns:android="http://www.easck.com/apk/res/android"
xmlns:tools="http://www.easck.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="cn.teachcourse.www.MainActivity"
android:orientation="vertical"
android:gravity="center"
android:id="@+id/onclick_ll" >
<!--点击LinearLayout控件,改变ProgressBar进度-->
<ProgressBar
android:id="@+id/progressBar_horizontal"
style="?android:attr/progressBarStyleHorizontal"
android:layout_width="match_parent"
android:layout_height="15dp"
android:layout_marginTop="28dp"/>

</LinearLayout>

在Java代码中非常的简单,如下图:

public class MainActivity extends ActionBarActivity implements View.OnClickListener{
private ProgressBar pb_large;
private ProgressBar pb_normal;
private ProgressBar pb_small;
private ProgressBar pb_horizontal;
private int readed;
private int progressValue;

private LinearLayout onclick_ll;

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

Drawable drawable = getResources().getDrawable(
R.drawable.progress_bar_states);

pb_horizontal.setProgressDrawable(drawable);//设置水平滚动条的样式

pb_horizontal.setMax(100);//设置进度条的最大值
onclick_ll.setOnClickListener(this);//LinearLayout添加监视器
}

private void initView() {
pb_horizontal = (ProgressBar) findViewById(R.id.progressBar_horizontal);
onclick_ll=(LinearLayout)findViewById(R.id.onclick_ll);
}

@Override
public void onClick(View v) {
pb_horizontal.incrementProgressBy(5);
if(pb_horizontal.getProgress()==pb_horizontal.getMax()){
Toast.makeText(this, "进度条已经达到最大值,进度条消失", Toast.LENGTH_LONG).show();
pb_horizontal.setProgress(0); //当达到最大之后,进度值归0
}
}
}