我正在尝试扩展 ViewPager2
类,以便可以左右拖动我的SeekBarPreference
。
class ViewPager2Custom(context: Context) : ViewPager2(context) {
}
但是我在
ViewPager2(context)
上得到了“此类型是最终类型,因此不能从它继承”红线。任何想法?
最佳答案
NestedScrollableHost类完全可以满足您的需求:https://github.com/android/views-widgets-samples/blob/master/ViewPager2/app/src/main/java/androidx/viewpager2/integration/testapp/NestedScrollableHost.kt
基本想法是,您重写onInterceptTouchEvent
并通过ViewPager2
方法请求NestedScrollableHost的父级(在本例中为requestDisallowInterceptTouchEvent
)不允许其拦截触摸事件。
// Pseudo-code for NestedScrollableHost
@Override
public boolean onInterceptTouchEvent(MotionEvent event) {
handleInterceptTouchEvent(event);
return super.onInterceptTouchEvent(event);
}
private void handleInterceptTouchEvent(MotionEvent event) {
// Early return if parent viewpager is null or child can't scroll in same direction as parent
if (getParentViewPager() == null ||
(!canChildScrollVertically(-1f) && !canChildScrollVertically(1f))) {
return;
}
switch (event.getAction()) {
// You can tailor your class to handle the event in the way you want to,
// e.g. do something on down and move events:
case MotionEvent.ACTION_DOWN:
// Disallow the parent (and all subsequent parents) to intercept touch events.
getParent().requestDisallowInterceptTouchEvent(disallow);
case MotionEvent.ACTION_MOVE:
// Some other logic.
}
}
您可以将NestedScrollableHost放在XML中的ViewPager2
和(在您的情况下)SeekBarPreference
之间。