【问题标题】:Implement interface using custom ScrollView class - Android使用自定义 ScrollView 类实现界面 - Android
【发布时间】:2017-01-04 12:27:25
【问题描述】:

我需要知道用户何时向上或向下滚动。我设法实现了这一点,但现在我无法将结果返回到我需要它的主类。具体来说,我不知道如何将结果传递给我创建的界面。

这是我得到的错误:

尝试调用接口方法'void com.app.android.interfaces.ScrollDirection.Down(int)' 空对象引用

这是我的自定义 ScrollView:

public class CustomScrollView extends ScrollView {

    private ScrollDirection scrolldirection;

    public CustomScrollView(Context context) {
        super(context);
        scrolldirection = (ScrollDirection) context;
    }

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

    public CustomScrollView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    @Override
    protected void onScrollChanged(int scrollX, int scrollY, int oldScrollX, int oldScrollY) {
        super.onScrollChanged(scrollX, scrollY, oldScrollX, oldScrollY);
        if(scrollY<oldScrollY){
            scrolldirection.Down(1);
        }else{
            scrolldirection.Down(-1);
        }
    }

    public interface ScrollDirection{
        public void Down(int direction);
    }
}

【问题讨论】:

  • 看来scrolldirection 还没有初始化。因此NullPointerException。将调试点放在您的构造函数中,玩得开心!

标签: java android interface


【解决方案1】:

您需要在每个构造函数中添加这一行 scrolldirection = (ScrollDirection) context;

public CustomScrollView(Context context, AttributeSet attrs) {
    super(context, attrs);
    scrolldirection = (ScrollDirection) context;
}

public CustomScrollView(Context context, AttributeSet attrs, int defStyleAttr) {
    super(context, attrs, defStyleAttr);
    scrolldirection = (ScrollDirection) context;
}

要允许 Android Studio 与您的视图交互,您至少必须提供一个以 Context 和 AttributeSet 对象作为参数的构造函数

Docs link

更新:最近的问题是在Fragment 内部实现CustomScrollView,但Fragment 没有它们的context。要实现这一点,请将父 Activity implements ScrollDirection 并在 Fragment 中创建一些函数并从 Activity's Down 函数中调用它们。

【讨论】:

  • 感谢您的回答。使用此代码时出现此错误:Binary XML file line #84: Binary XML file line #84: Error inflating class com.app.android.supportClass.CustomScrollView.
  • 尝试清理并运行选项
  • 我唯一改变的是xml中的ScrollView到com.app.android.supportClass.CustomScrollView
  • supportClass是我用来存放CustomScrollView的包
  • 在你的`XML`中应该是这样&lt;your_class_packagename.CustomScrollView
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-06-25
  • 1970-01-01
  • 2016-07-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多