要使用代碼控制 ProgressBar 的進度,您需要首先在布局文件中添加一個 ProgressBar 元素
android:id="@+id/progressBar"
style="?android:attr/progressBarStyleHorizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:max="100"/>
import android.os.Bundle;
import android.widget.ProgressBar;
public class MainActivity extends AppCompatActivity {
private ProgressBar progressBar;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
progressBar = findViewById(R.id.progressBar);
// 設置進度值
int progressValue = 50;
progressBar.setProgress(progressValue);
}
}
這樣,當您運行應用程序時,ProgressBar 將顯示為當前設置的進度值。在這個例子中,ProgressBar 的進度為50%。
注意:請確保在實際應用中根據需求動態地更新進度值。例如,您可以在后臺線程中執行耗時任務并根據任務完成情況更新 ProgressBar 的進度。