ViewPager prohibits sliding effect realization

Write in front

When the project first started, PM: You don’t need to slide, it’s too fancy. . .
Me: Now mainstream apps can generally slide, which is more in line with user habits...
Now, PM: Why can’t you slide, it doesn’t meet user needs, so quickly change it. . .
I:…

Anyway, I wrote it all, or throw it out for everyone to see

Rewrite the method of ViewPager

I am using ViewPager+FragmentPagerAdapter

Disabling the sliding effect is quite simple, just rewrite the ViewPager method.

First define a boolean value to mark, whether to allow sliding.

// 是否滑动,用来标记
    private boolean isCanScroll = true;

Set whether to allow sliding in subclasses that inherit it

    public void setCanScroll(boolean canScroll) {
        isCanScroll = canScroll;
    }

Override the interception method of ViewPager. This is an interception method for event processing, which can change the direction of event delivery. It determines whether the Touch event is delivered to the child control.

If false is returned, it will not be intercepted and passed to the child control.
If true is returned, it will be intercepted and processed by its own onTouchEvent

super.onInterceptTouchEvent(ev), the default is return true.

    @Override
    public boolean onInterceptTouchEvent(MotionEvent ev) {
        return isCanScroll && super.onInterceptTouchEvent(ev);
    }

Override the processing method of ViewPager, this method determines whether the current control consumes this event

If it returns false, it means that there is no consumption and will be uploaded layer by layer.
If it returns true, it means it has been consumed and the event is over.

super.onTouchEvent(ev), the default return is false.

    @Override
    public boolean onTouchEvent(MotionEvent ev) {
        return isCanScroll && super.onTouchEvent(ev);
    }

use

In the Activity to use ViewPager

// 使用CustomViewPager 继承ViewPager
    private CustomViewPager container;

In onCreate method

// 禁止左右滑动
        container.setCanScroll(false);

In the layout file.xml

<!-- 禁用滑动导航菜单页 -->
    <com.巴拉巴拉.common.view.CustomViewPager
        android:id="@+id/containerVP"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="1" />

Through the above steps, you can disable the left and right sliding effect of ViewPager.

Ps:
Regarding Android's onInterceptTouchEvent() and onTouchEvent(), this old man's blog writes very detailed.
Detailed interception and processing methods

Rewrite file download address

Guess you like

Origin blog.csdn.net/A_Intelligence/article/details/85164757