ProgressBar用于在界面上显示一个进度条,表示我们的程序正在加载一些数据
activity_main.xml
<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">
<Button
android:id="@+id/btn"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="点我啊" />
<ProgressBar
android:id="@+id/progras_bar"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</LinearLayout>
<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">
<Button
android:id="@+id/btn"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="点我啊" />
<ProgressBar
android:id="@+id/progras_bar"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</LinearLayout>
所有的Android控件都具有这个属性,可以通过android:visibility进行指定,可选值有三种,visible、invisible和gone。visible表示控件是可见的,这个值是默认值,不指定android:visibility时,控件都是可见的。invisible表示控件不可见,但是它仍然占据着原来的位置和大小,可以理解成控件变成透明状态了。gone则表示控件不仅不可见,而且不再占用任何屏幕空间。
MainActivity.java
public class MainActivity extends Activity implements View.OnClickListener {
private Button btn;
private ProgressBar progressBar;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initView();
}
/**
* 初始化控件
*/
private void initView() {
btn = (Button) findViewById(R.id.btn);
progressBar = (ProgressBar) findViewById(R.id.progras_bar);
btn.setOnClickListener(this);
}
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.btn:
if (progressBar.getVisibility() == View.GONE) {
progressBar.setVisibility(View.VISIBLE);
} else {
progressBar.setVisibility(View.GONE);
}
break;
}
}
}
运行结果
在按钮的点击事件中,我们通过getVisibility()方法来判断ProgressBar是否可见,如果可见就将ProgressBar隐藏掉,如果不可见就将ProgressBar显示出来。重新运行程序,然后不断地点击按钮,你就会看到进度条会在显示与隐藏之间来回切换。
另外,我们还可以给ProgressBar指定不同的样式,刚刚是圆形进度条,通过style属性可以将它指定成水平进度条
<ProgressBar
android:id="@+id/progras_bar"
style="?android:attr/progressBarStyleHorizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:max="100" />
指定成水平进度条后,我们还可以通过android:max属性给进度条设置一个最大值,然后在代码中动态地更改进度条的进度
修改MainActivity.java
case R.id.btn:
int progress = progressBar.getProgress();
progress = progress + 10;
progressBar.setProgress(progress);
break;
每点击一次按钮,我们就获取进度条的当前进度,然后在现有的进度上加10作为更新后的进度。重新运行程序,点击数次按钮后,运行效果如下