Android中如何实现滚动条向上/向下时标题栏隐藏/显示?

问题描述 投票:0回答:1

https://i.imgur.com/i8n8t1e.mp4

与twitter应用一样,标题栏随着滚动条的滚动逐渐隐藏和显示。如何实现?

我搜索了底部栏问题但找不到标题栏解决方案。

我想使用MAUI来实现这个功能,但我不知道从哪里开始。我希望得到您的帮助。

谢谢。

android maui titlebar
1个回答
0
投票

最简单的方法是只需使用

ScrollView
并隐藏和显示导航栏。问题是触摸屏的闪烁和灵敏度。因此,您需要考虑节流阀或我使用的去抖计时器(当您希望事件不经常或快速发生时通常使用。)下面的代码是一个简单的概念证明。更好的方法是使用动画并进行真正的控制,但随后您需要使用处理程序和本机代码。

xaml

<ScrollView x:Name="myScrollView" Scrolled="OnScrolled">
    <StackLayout x:Name="myStackLayout" />
</ScrollView>

代码

public partial class TestView : ContentPage
{
    private double _lastScrollY;

    public TestView()
    {
        InitializeComponent();

        for (int i = 1; i <= 30; i++)
        {
            myStackLayout.Children.Add(new Label
            {
                Text = $"Item {i}",
                FontSize = 20,
                Margin = new Thickness(10),
                HeightRequest = 50, 
                BackgroundColor = Colors.LightGray,
                HorizontalOptions = LayoutOptions.Center
            });
        }
    }

    private IDispatcherTimer _debounceTimer;
    private bool _isAnimating = false;

    private void OnScrolled(object sender, EventArgs e)
    {
        if (_isAnimating) return; 

        var direction = myScrollView.ScrollY - _lastScrollY;
        _lastScrollY = myScrollView.ScrollY;

        _debounceTimer?.Stop();

        _debounceTimer = Application.Current.Dispatcher.CreateTimer();
        _debounceTimer.Interval = TimeSpan.FromMilliseconds(60);

        _debounceTimer.Tick += (s, eventArgs) =>
        {
            _isAnimating = true; 

            if (direction > 0) 
            {
                HideNavigationBar();
            }
            else if (direction < 0) 
            {
                ShowNavigationBar();
            }

            _isAnimating = false; 
            _debounceTimer.Stop();
        };
        _debounceTimer.Start();
    }

    private void HideNavigationBar()
    {
        Shell.SetTabBarIsVisible(this, false);
        Shell.SetNavBarIsVisible(this, false);
    }

    private void ShowNavigationBar()
    {
        Shell.SetTabBarIsVisible(this, true);
        Shell.SetNavBarIsVisible(this, true);
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.