📅  最后修改于: 2023-12-03 14:59:15.069000             🧑  作者: Mango
SeekBar is a UI component in Android for selecting a value from a range of values. In this tutorial, we will learn how to use SeekBar in Java Android.
To create a SeekBar, we first need to add the following code in the XML layout file:
<SeekBar
android:id="@+id/seek_bar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:max="100"
android:progress="50"/>
We can customize the SeekBar by changing the max
value, progress
value, and layout_width
and layout_height
attributes.
After adding the SeekBar to the layout file, we need to reference it in the Java file using findViewById()
method:
SeekBar seekBar = findViewById(R.id.seek_bar);
We can listen to the SeekBar changes using setOnSeekBarChangeListener()
method. We can override the methods onProgressChanged()
, onStartTrackingTouch()
, and onStopTrackingTouch()
to listen to the SeekBar changes:
seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
@Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
// Do something when the SeekBar progress is changed
}
@Override
public void onStartTrackingTouch(SeekBar seekBar) {
// Do something when user starts touching the SeekBar
}
@Override
public void onStopTrackingTouch(SeekBar seekBar) {
// Do something when user stops touching the SeekBar
}
});
To retrieve the current value of the SeekBar, we can use the getProgress()
method:
int seekBarValue = seekBar.getProgress();
In this tutorial, we learned how to use SeekBar in Java Android. We learned how to create a SeekBar, listen to its changes, and retrieve its value. SeekBar is an essential component for inputting values from the user in Android applications.