神刀安全网

AutoHide FloatingActionButton in Xamarin.Android

My main phone is an Android and as a news app I use a 3rd party aggregator that, al nearly all Android apps today is based on Material Design .

Using it everyday I couldn’t ignore a nice UI feature it exposes: it’s share button (a Material Design’s FloatinActionButton) fades out when you scroll the list vertically and it reappears when you scroll the list down.

Being curious, I wanted to know how to create that effect using Xamarin.Android.

This is my final result:

AutoHide FloatingActionButton in Xamarin.Android

Since there’s a lot of setup involved I won’t go too much into code detail and setup, you can grab the project source code from here https://github.com/corradocavalli/Xamarin.Android.HideMyFAB

I’m assuming you have some basic knowledge of Material Design and  related steps to enable it into a Xamarin.Android app so and I’ll go straight to the point: The view you see is made up of a CoordinatorLayout that hosts a NestedScrollView that contains a series of CardViews and in the bottom right corner there is our FloatingActionButton.

The trick of making it disappear is to add a custom behavior so that CoordinatorLayout knows that it has to invoke a behavior that takes care to hide/show it when something happen, in our case when user scrolls up or down.

This is the required behavior

Inside OnNestedStartScroll we inform the CoordinatorLayout that we want to receive scroll events when user scrolls vertically while inside OnNestedScroll we receive a reference to the FloatingActionButton (since we have applied the behavior to it) and depending on scroll direction we show/hide it.

The hard part of migrating this code to Xamarin was fixing the weird compilation issues I was having, I thank community guy fex for giving me the hint to add the [Register] attribute at the top to the class definition and inheriting from CoordinatorLayout instead of my initial FloatingAction. No idea if this is a bug, I’ve seen someone already filed it on Bugzilla but still without any reply.

Is now time to associate out behavior to the FloatinActionButton, I’ll do that using the standard approach to define the fully qualified path to the class inside strings.xml for better refactoring.

and now it’s just a matter of attach it to the button

If you use material design in your appls you’ll immediately recognize the now stanrdard elements, the only real new is the layout_behavior attribute applied to the FloatingActionButton that points to our custom behavior.

There are indeed simpler alternatives like James Montemagno component available here but looks like it is now deprecated and I think that, once you know how to fix the ACW compilation issues, knowing how to use material design behaviors wont hurt.

Enjoy AutoHide FloatingActionButton in Xamarin.Android

转载本站任何文章请注明:转载至神刀安全网,谢谢神刀安全网 » AutoHide FloatingActionButton in Xamarin.Android

分享到:更多 ()

评论 抢沙发

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址