Using new material design slider com.google.android.material.slider.Slider
. The documentation is quite poor for it as it has been just recently released. Trying to get value from slider but no luck for now. In other words, what would be a slider's equivalent of setOnProgressChanged { }
from Seekbar.
You can use the OnChangeListener
listener
slider.addOnChangeListener(new Slider.OnChangeListener() {
@Override
public void onValueChange(@NonNull Slider slider, float value, boolean fromUser) {
//Use the value
}
});
Slider slider = findViewById(R.id.slider);
slider.addOnSliderTouchListener(touchListener);
Then
private final OnSliderTouchListener touchListener =
new OnSliderTouchListener() {
@Override
public void onStartTrackingTouch(Slider slider) {
}
@Override
public void onStopTrackingTouch(Slider slider) {
}
};
For more details, Check SliderMainDemoFragment.java
To get value updates you can use Slider.OnChangeListener
:
val slider = Slider(requireContext())
slider.addOnChangeListener { slider, value, fromUser -> /* `value` is the argument you need */ }
// the same implementation with interface name
// slider.addOnChangeListener(Slider.OnChangeListener { slider, value, fromUser -> })
Examples of slider implementation from Material Components official repository.
We can get the value of the slider using addOnChangeListener.
The parameter value is of type Float.
slider.addOnChangeListener { slider, value, fromUser ->
Toast.makeText(baseContext, value.toString(), Toast.LENGTH_LONG).show()
}
If I'm right you are trying to get the value of the Slider
on the go.
As far as I can see there is no direct method for that, but we can utilize a Labelformatter
to do so.
A Labelformatter
gets the value of the Slider
, modifies it and returns it so that it can be displayed in the label above the Slider
. In there you can add you lines of code processing the value.
Create a Labelformatter
:
formatter = new LabelFormatter() {
@NonNull
@Override
public String getFormattedValue(float value) {
//do what you want with the value in here...
return "" + value;
}
};
Afterwards just add the Labelformatter
to your Slider
with
slider.setLabelFormatter(formatter);
Caution: This only works when you choose to show the label on the Slider
Edit:
If you don't want the label to show up, you will have to create your own style for the label making it invisible.
Create a style in styles.xml
:
<style name="LabelStyle" parent="ShapeAppearance.Material3.Tooltip"> //parent might be different for you
<item name="android:textColor">@color/transparent</item>
<item name="backgroundTint">@color/transparent</item>
</style>
Finally, add the style to the label in the xml of your layout
<com.google.android.material.slider.Slider
...
app:labelStyle="@style/LabelStyle"/>
© 2022 - 2024 — McMap. All rights reserved.