ScrollView 的 OnScrollChangeListener

OnScrollChangeListener for ScrollView

我想做一个函数来拦截视图顶部的某个滚动条。 为此,我尝试使用 OnScrollChangeListener。 我的视图包含一个 ScrollView

<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/scrollViewClientPhysique"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@color/fond"
tools:context=".client.FicheClient">

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical">**strong text**

然后我在 onCreateView

中调用的函数中初始化 addOnScrollChangedListener
    fun initializeInfiniteScroll(){
    val scrollView = myView.findViewById<View>(R.id.scrollViewClientPhysique) as ScrollView

    scrollView.viewTreeObserver.addOnScrollChangedListener {
        if (scrollView != null) {
            val view = scrollView.getChildAt(scrollView.childCount - 1)
            val diff =
                view.bottom + scrollView.paddingBottom - (scrollView.height + scrollView.scrollY)

            if (diff == 0) {
                // do stuff
                }
            }
        }
     }

但是当我滚动视图时,我没有输入 addOnScrollChangedListener 来拦截滚动的 dp。

我做错了什么?

请按如下所述更新您的 ScrollChangedListener。

    public class MainActivity extends AppCompatActivity implements View.OnTouchListener,
       ViewTreeObserver.OnScrollChangedListener {
       ScrollView scrollView;
       @Override
       protected void onCreate(Bundle savedInstanceState) {
          super.onCreate(savedInstanceState);
          setContentView(R.layout.activity_main);
          scrollView = findViewById(R.id.scrollView);
          scrollView.setOnTouchListener(this);
          scrollView.getViewTreeObserver().addOnScrollChangedListener(this);
       }
       public void onScrollChanged(){
          View view = scrollView.getChildAt(scrollView.getChildCount() - 1);
          int topDetector = scrollView.getScrollY();
          int bottomDetector = view.getBottom() - (scrollView.getHeight() + scrollView.getScrollY());
          //TODO: Just added for testing/understanding. Please add/replace your own logic..
          if(bottomDetector == 0 ){
             Toast.makeText(this,"Scroll View bottom reached",Toast.LENGTH_SHORT).show();
          }
          if(topDetector <= 0){
             Toast.makeText(this,"Scroll View top reached",Toast.LENGTH_SHORT).show();
          }
       }
       @Override
       public boolean onTouch(View v, MotionEvent event) {
          return false;
       }
    }