<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" tools:context=".MainActivity"> <ProgressBar android:id="@+id/pb" android:layout_width="wrap_content" android:layout_height="wrap_content" /> <Button android:onClick="myClick" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="显示隐藏进度条"/> <!-- 想有一点点加载的效果就得设置max--> <ProgressBar android:id="@+id/pb2" style="?android:attr/progressBarStyleHorizontal" android:max="100" android:layout_width="300dp" android:layout_height="wrap_content"/> <Button android:onClick="myLoder" android:text="模拟下载,增加一点" android:layout_width="wrap_content" android:layout_height="wrap_content"/> <ProgressBar android:id="@+id/pb3" style="?android:attr/progressBarStyleHorizontal" android:max="100" android:layout_width="300dp" android:indeterminate="true" android:layout_height="wrap_content"/> </LinearLayout>
package com.example.myprogressbar2; import androidx.appcompat.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.ProgressBar; public class MainActivity extends AppCompatActivity { private ProgressBar progressBar; private ProgressBar progressBar2; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); progressBar = findViewById(R.id.pb); } public void myClick(View view) { //进度条目前没显示则让他显示 if (progressBar.getVisibility() == View.GONE){ progressBar.setVisibility(View.VISIBLE); }else { progressBar.setVisibility(View.GONE); } } public void myLoder(View view) { progressBar2 = findViewById(R.id.pb2); //获取进度条的值(进度) int progress = progressBar2.getProgress(); progress+=10; progressBar2.setProgress(progress); } }