英文:
Casting custom ScrollView to ScrollView
问题
我有一个自定义的滚动视图,看起来像这样:
public class PagerScrollView extends ScrollView {
float touchX = 0;
float touchY = 0;
ViewPager parentPager;
public void setParentPager(ViewPager parentPager) {
this.parentPager = parentPager;
}
public PagerScrollView(Context context, AttributeSet attrs) {
super(context, attrs);
}
public PagerScrollView(Context context) {
super(context);
}
@Override
public boolean onTouchEvent(MotionEvent ev) {
switch (ev.getActionMasked()) {
case MotionEvent.ACTION_DOWN:
touchX = ev.getX();
touchY = ev.getY();
return super.onTouchEvent(ev);
case MotionEvent.ACTION_MOVE:
if (Math.abs(touchX - ev.getX()) < 40) {
return super.onTouchEvent(ev);
} else {
if (parentPager == null) {
return false;
} else {
return parentPager.onTouchEvent(ev);
}
}
case MotionEvent.ACTION_CANCEL:
case MotionEvent.ACTION_UP:
touchX = 0;
touchY = 0;
break;
}
return super.onTouchEvent(ev);
}
}
在 XML 中,我将它包裹在一个 ViewPager 和一个 TabLayout 中(也许这是错误的原因?)。当我尝试使用以下代码进行分配时:
PagerScrollView pagerScrollView = rootView.findViewById(R.id.pager_scroll_view);
我得到以下错误:
android.widget.ScrollView cannot be cast to exampleapplication.PagerScrollView
如何正确地进行类型转换?
英文:
I have got a custom scrollview that looks like this:
public class PagerScrollView extends ScrollView {
float touchX = 0;
float touchY = 0;
ViewPager parentPager;
public void setParentPager(ViewPager parentPager) {
this.parentPager = parentPager;
}
public PagerScrollView(Context context, AttributeSet attrs) {
super(context, attrs);
}
public PagerScrollView(Context context) {
super(context);
}
@Override
public boolean onTouchEvent(MotionEvent ev) {
switch (ev.getActionMasked()) {
case MotionEvent.ACTION_DOWN:
touchX = ev.getX();
touchY = ev.getY();
return super.onTouchEvent(ev);
case MotionEvent.ACTION_MOVE:
if (Math.abs(touchX-ev.getX()) < 40) {
return super.onTouchEvent(ev);
} else {
if (parentPager == null) {
return false;
} else {
return parentPager.onTouchEvent(ev);
}
}
case MotionEvent.ACTION_CANCEL:
case MotionEvent.ACTION_UP:
touchX = 0;
touchY = 0;
break;
}
return super.onTouchEvent(ev);
}
}
In the xml, I wrap it around a ViewPager and a TabLayout (maybe this is the error?). When I try to assign it using
PagerScrollView pagerScrollView = rootView.findViewById(R.id.pager_scroll_view);
I get:
android.widget.ScrollView cannot be cast to exampleapplication.PagerScrollView
How can I cast it correctly?
答案1
得分: 0
问题在于我在XML中使用了普通的ScrollView,而不是我的<exampleapplication.CustomScrollView>。替换后,问题得以解决。
英文:
The issue was that I used a normal ScrollView in the xml instead of my <exampleapplication.CustomScrollView>. Replacing that fixed my problem.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论