问题
Hello,
i want to change a view's padding according to bottomSheet's slideOffset.
But when i tried to change view's padding on BoottomSheetBehaviour Callback, BottomSheet sliding speed goes slow down. here is my code:
View bottomSheet = coordinatorLayout.findViewById(R.id.bottom_sheet);
behavior = BottomSheetBehavior.from(bottomSheet);
behavior.setBottomSheetCallback(new BottomSheetBehavior.BottomSheetCallback() {
@Override
public void onStateChanged(@NonNull View bottomSheet, int newState) {
if (newState == BottomSheetBehavior.STATE_COLLAPSED) {
bottomSheetExpended = false;
} else if (newState == BottomSheetBehavior.STATE_EXPANDED) {
bottomSheetExpended = true;
}
}
@Override
public void onSlide(@NonNull View bottomSheet, float slideOffset) {
int padding = (int) (10 * slideOffset);
nestedScrollView.setPadding(padding, 0, padding, 0);
}
});
Trying to change nestedScrollview's Padding.
How to solve this problem?
回答1:
The slideOffset goes from 0 to 1 as you slide up and from 1 to 0 as you slide down. If you have want to go from having padding to no padding as you slide up and from no padding to having padding as you slide down, then do it like this.
View bottomSheet = coordinatorLayout.findViewById(R.id.bottom_sheet);
behavior = BottomSheetBehavior.from(bottomSheet);
// Get Padding value outside of onSlide
final float originalPadding = getActivity().getResources().getDimension(R.dimen.original_padding);
behavior.setBottomSheetCallback(new BottomSheetBehavior.BottomSheetCallback() {
@Override
public void onStateChanged(@NonNull View bottomSheet, int newState) {
if (newState == BottomSheetBehavior.STATE_COLLAPSED) {
bottomSheetExpended = false;
} else if (newState == BottomSheetBehavior.STATE_EXPANDED) {
bottomSheetExpended = true;
}
}
@Override
public void onSlide(@NonNull View bottomSheet, float slideOffset) {
nestedScrollView.setPadding(Math.round(originalPadding * (1 - slideOffset)),
0, Math.round(originalPadding * (1 - slideOffset)), 0);
}
});
To do it the opposite way, just don't subtract 1 from the slide offset.
Note: I am only using Math.round() because I am getting the padding as a float from the dimens resources outside of onSlide().
Don't do anything too resource intensive inside of onSlide() because it gets called a bunch and that could be the reason your bottomsheet is sliding slowly even though it doesn't look like you are doing that here.
Also, you don't need to keep track of the Bottom Sheet's state because you can always call:
if (behavior.getState() == BottomSheetBehavior.STATE_EXPANDED) {
// Bottom sheet is expanded
}
else if (behavior.getState() == BottomSheetBehavior.STATE_COLLAPSED) {
// Bottom sheet is collapsed
}
The onStateChanged() method is more for reacting to the state being changed with things like showing or hiding other views, etc.
来源:https://stackoverflow.com/questions/48443350/bottomsheet-sliding-very-slowly