android - 当 ScrollView 滚动到底部时加载更多数据

标签 android android-scrollview

我有一个动态加载内容的 ScrollView 。有时可能会有很多内容,所以我想在用户滚动到底部时加载更多内容。

我搜索了合适的方法,找到了两个:

onScrollChanged() 

getScrollY()

但我不知道如何将它用于我的目的。 请给我一些建议。

最佳答案

ScrollView 不提供任何方法来检查您是否已到达 View 底部,因此最好的技术是使用 ScrollView 扩展您自己的自定义 View 。这就是我在我的应用程序中实现的方式。

第 1 步:为 ScrollView 创建自定义类

public class ObservableScrollView extends ScrollView {

private ScrollViewListener scrollViewListener = null;

public ObservableScrollView(Context context) {
    super(context);
}

public ObservableScrollView(Context context, AttributeSet attrs, int defStyle) {
    super(context, attrs, defStyle);
}

public ObservableScrollView(Context context, AttributeSet attrs) {
    super(context, attrs);
}

public void setScrollViewListener(ScrollViewListener scrollViewListener) {
    this.scrollViewListener = scrollViewListener;
}

@Override
protected void onScrollChanged(int x, int y, int oldx, int oldy) {

    View view = (View) getChildAt(getChildCount() - 1);
    int diff = (view.getBottom() - (getHeight() + getScrollY()));
    if (diff == 0) { // if diff is zero, then the bottom has been reached
        if (scrollViewListener != null) {
            scrollViewListener.onScrollEnded(this, x, y, oldx, oldy);
        }
    }
    super.onScrollChanged(x, y, oldx, oldy);
}

第二步:创建 ScrollView 监听器界面

public interface ScrollViewListener {

void onScrollEnded(ObservableScrollView scrollView, int x, int y, int oldx, int oldy);



 }

第 3 步:在布局中添加 View

   <com.platinumapps.facedroid.ObservableScrollView
        android:id="@+id/scrollView"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent" >
    </com.platinumapps.facedroid.ObservableScrollView>

第 4 步:在您的类中实现该接口(interface)

  public class MyFragment extends Fragment implements ScrollViewListener 

@Override
public void onScrollEnded(ObservableScrollView scrollView, int x, int y, int oldx,   int oldy) {

           //Perform your action
}

你完成了

关于android - 当 ScrollView 滚动到底部时加载更多数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14774121/

相关文章:

java - 尝试在空对象引用上调用虚拟方法 'void android.widget.ImageView.setVisibility(int)'

java - Gson.toJson 返回 null [ProGuard 问题]

android - 在 Android 中创建锁定的 ScrollView

android - 检测 ScrollView 是否向上或向下滚动 - Android

android - 从首选项屏幕启动 Activity (在 xml 文件中定义的 Intent )

android - 如何将 Java.IO.FileOutputStream 写入 photo.Compress(Bitmap.CompressFormat.Png, 100, outputstream)?

android - 在Android的kotlin类中遇到多个错误?

Android - 向布局添加 View

android - Recyclerview 在滚动期间更改项目

android - 启用 ScrollView 弹跳内容