material-components-android icon indicating copy to clipboard operation
material-components-android copied to clipboard

[BottomSheetBehavior] Add method to calculate slide offset

Open OxygenCobalt opened this issue 3 years ago • 3 comments

Add a calculateSlideOffset method to BottomSheetBehavior, allowing the current slide offset to be obtained at runtime.

I have several runtime transitions dependent on the offset of my bottom sheet. However, these transitions need to be initialized on startup, something that can't be provided by BottomSheetCallback as it does not fire on startup. Since making that callback fire on startup would break compatibility, instead I want a way to get the slide offset so I can initialize the components myself.

This PR resolves that by adding a method (calculateSlideOffset) that returns the current slide offset of the bottom sheet. If the sheet is not laid out, it will return 0.

Resolves #2871.

OxygenCobalt avatar Jul 28 '22 21:07 OxygenCobalt

I'm not too familiar with android unit testing @drchen.

  1. ~~How do I run the tests? There's no specific option in android studio for me to run them.~~ Nevermind, ./gradlew lib:test does it.

  2. Is a test like this appropriate? I gleamed other implementations to create it, however I'm not sure how correct or rigorous it is.


  @Test
  @SmallTest
  public void testCalculateSlideOffset() {
    activityTestRule.runOnUiThread(
        () -> {
          BottomSheetBehavior<?> behavior = getBehavior();
          behavior.setState(BottomSheetBehavior.STATE_EXPANDED);
          assertThat(behavior.calculateSlideOffset(), is(1f));
          behavior.setState(BottomSheetBehavior.STATE_HALF_EXPANDED);
          assertThat(behavior.calculateSlideOffset(), is(0.5f));
          behavior.setState(BottomSheetBehavior.STATE_COLLAPSED);
          assertThat(behavior.calculateSlideOffset(), is(0f));
          behavior.setState(BottomSheetBehavior.STATE_HIDDEN);
          assertThat(behavior.calculateSlideOffset(), is(-1f));
        });
  }

I did run the tests and it seemed to have succeeded.

OxygenCobalt avatar Jul 29 '22 17:07 OxygenCobalt

You can probably just run ./gradlew test to run all unit tests? (Sorry I'm not entirely familiar with how to run a single test from gradle but it shouldn't take too long to run all of them.)

drchen avatar Jul 29 '22 18:07 drchen

Yeah, I was able to run the tests @drchen. The test I made seemed to pass (No errors with ./gradlew test), so I pushed the change.

OxygenCobalt avatar Jul 29 '22 18:07 OxygenCobalt