简体   繁体   English

RecyclerView滚动到顶部按钮

[英]RecyclerView scroll to top button

I want to add back to top button in my app. 我想在我的应用中添加回到顶部按钮。 I use recyclerview for displaying items. 我使用recyclerview显示项目。 I added button and when I click on it, view is going to top, but my goal is to show this button only if application is scrolled down or up, and my first item is not visible (I hope thats clear explanation). 我添加了按钮,当我单击它时,视图将移至顶部,但是我的目标是仅在应用程序向下或向上滚动且我的第一项不可见时才显示此按钮(希望那能有清楚的解释)。 I tried with 我尝试过

LayoutManager.findFirstCompletelyVisibleItemPosition();

and other methods for LayoutManager but without acceptable effects. 和其他用于LayoutManager的方法,但没有可接受的效果。

My solution is showed below. 我的解决方案如下所示。 I add OnScrollListener on my RecyclerView, and when view is scrolled I check if the first item is visible and I set visibility of my button. 我在RecyclerView上添加OnScrollListener,然后在滚动视图时检查第一项是否可见,并设置按钮的可见性。

MyRecyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
    @Override
    public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
        super.onScrollStateChanged(recyclerView, newState);
    }

    @Override
    public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
        int visibility = (MyLayoutManager.findFirstCompletelyVisibleItemPosition() != 0) ? View.VISIBLE : View.GONE;
        btn.setVisibility(visibility);
    }
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM