所以我试图实现一个FAB按钮,以便当我滚动回收器视图并且第一项不可见(向上滚动等)时,fab按钮应该可见,否则,如果显示第一个位置,则应将其隐藏。现在我已经实现了代码,但是它根本不显示fab按钮,只是想知道我在做什么错?

我的xml代码如下:

<Linearlayout ....


    <FrameLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent">
        <android.support.v4.widget.SwipeRefreshLayout
            xmlns:android="http://schemas.android.com/apk/res/android"
            android:id="@+id/pullToRefreshLayout"
            android:layout_width="match_parent"
            android:layout_height="match_parent">

            <android.support.v7.widget.RecyclerView
                android:id="@+id/myRecyclerView"
                android:layout_width="match_parent"
                android:layout_height="match_parent" />

        </android.support.v4.widget.SwipeRefreshLayout>

            <android.support.design.widget.FloatingActionButton
                android:id="@+id/emailFab"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_margin="16dp"
                android:src="@android:drawable/ic_dialog_email"
                app:layout_anchor="@id/myRecyclerView"
                android:layout_gravity="bottom|end"
                app:layout_behavior="com.example.fab.ScrollAwareFABBehavior"
                app:layout_anchorGravity="bottom|end"
                />
        </FrameLayout>

</LinearLayout>


我的Kotlin代码如下:

val positionView = (myRecyclerView.getLayoutManager() as LinearLayoutManager).findFirstVisibleItemPosition()

myRecyclerView.addOnScrollListener(object : RecyclerView.OnScrollListener() {
            override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) {
                super.onScrolled(recyclerView, dx, dy)
                if (dy >0 && positionView > 0) {
                    emailFab.show();
                } else  {
                    emailFab.hide();
                }
            }


任何想法如何去做?

谢谢!

最佳答案

我认为问题在于您应将findFirstVisibleItemPosition()拉入OnScrollListener以在滚动更改中找到可见位置:

myRecyclerView.addOnScrollListener(object : RecyclerView.OnScrollListener() {

        override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) {
            super.onScrolled(recyclerView, dx, dy)

            val positionView = (myRecyclerView.getLayoutManager() as LinearLayoutManager).findFirstVisibleItemPosition()

            if (positionView > 0) {
                if(!emailFab.isShown) {
                    emailFab.show();
                }
            } else  {
                if(emailFab.isShown) {
                    emailFab.hide();
                }
            }
        }
    })

10-05 21:11
查看更多