Android disables the sliding of the left and right sides of ViewPager
Sometimes there are some "weird" requirements during development, such as embedding ListView in ViewPager or embedding another ViewPager, when sliding, the embedded XXView cannot be moved. Now, we will disable sliding of the ViewPager on the outermost layer so that the embedded XXView can get the sliding event. There are also many online statements about the solution, which are basically the same, but you need to understand the event distribution mechanism in Android and do not understand the event distribution mechanism, check out some information on the Internet, and I will give a brief introduction here. Please refer to the blogAndroid custom control-slide menu.
How can I disable the sliding of ViewPager between the left and right sides? In general, ViewPager is rewritten to overwrite the onInterceptTouchEvent (MotionEvent arg0) method and onTouchEvent (MotionEvent arg0) method of ViewPager. The return values of these two methods are of the boolean type. You only need to change the return value to false, then ViewPager will not consume the finger slide event, and then pass it to the upper View for processing or the event will be terminated directly. Below is my custom ViewPager.
public class NoScrollViewPager extends ViewPager {private boolean noScroll = false;public NoScrollViewPager(Context context, AttributeSet attrs) {super(context, attrs);// TODO Auto-generated constructor stub}public NoScrollViewPager(Context context) {super(context);}public void setNoScroll(boolean noScroll) {this.noScroll = noScroll;}@Overridepublic void scrollTo(int x, int y) {super.scrollTo(x, y);}@Overridepublic boolean onTouchEvent(MotionEvent arg0) {/* return false;//super.onTouchEvent(arg0); */if (noScroll)return false;elsereturn super.onTouchEvent(arg0);}@Overridepublic boolean onInterceptTouchEvent(MotionEvent arg0) {if (noScroll)return false;elsereturn super.onInterceptTouchEvent(arg0);}@Overridepublic void setCurrentItem(int item, boolean smoothScroll) {super.setCurrentItem(item, smoothScroll);}@Overridepublic void setCurrentItem(int item) {super.setCurrentItem(item);}}
The above code is very simple. You can copy it directly without any modifications. For ease of operation, I set a boolean-type control variable in this custom ViewPager, and provided a method to control whether ViewPager is slide prohibited. This makes it more flexible. The following is the definition of custom ViewPager in the layout file.
Well, this is very simple and you don't need to introduce it too much. Code can be directly copied for use. The layout or data adapter PagerAdapter is exactly the same as ViewPager. Well, if you have any suggestions, please leave a message below. I am happy to learn and make progress together!