通过用手指在ViewPager刷卡如何禁用分页,但仍然可以刷卡编程? [英] How do disable paging by swiping with finger in ViewPager but still be able to swipe programmatically?

查看:137
本文介绍了通过用手指在ViewPager刷卡如何禁用分页,但仍然可以刷卡编程?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有ViewPager和它下面我有10个按钮。通过点击按钮,比如#4,寻呼机立即转到页#4中 mPager.setCurrentItem(3); 。但是,我想通过用手指横向轻扫禁用分页。因此,寻呼完成的通过点击按钮。 所以,我怎么可以用手指禁用刷卡?

I have ViewPager and below it I have 10 buttons. By clicking on button, for example #4, the pager goes immediately to page #4 by mPager.setCurrentItem(3);. But, I want to disable the paging by swiping with finger horizontally. Thus, the paging is done ONLY by clicking on the buttons. So, how I can disable the swiping with finger?

推荐答案

您需要继承ViewPager。的onTouchEvent有很多,你不希望改变,比如让孩子的意见得到触摸它的好东​​西。 onInterceptTouchEvent是你想改变。如果你看一下$ C $下ViewPager,你会看到评论:

You need to subclass ViewPager. onTouchEvent has a lot of good things in it that you don't want to change, like allowing child views to get touches. onInterceptTouchEvent is what you want to change. If you look at the code for ViewPager, you'll see the comment:

    /*
     * This method JUST determines whether we want to intercept the motion.
     * If we return true, onMotionEvent will be called and we do the actual
     * scrolling there.
     */

下面是一个完整的解决方案:

Here's a complete solution:

首先,这个类添加到您的src文件夹:

First, add this class to your src folder:

package com.yourcompany;

import android.content.Context;
import android.support.v4.view.ViewPager;
import android.util.AttributeSet;
import android.view.MotionEvent;

public class NonSwipeableViewPager extends ViewPager {

    public NonSwipeableViewPager(Context context) {
        super(context);
    }

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

    @Override
    public boolean onInterceptTouchEvent(MotionEvent event) {
        // Never allow swiping to switch between pages
        return false;
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        // Never allow swiping to switch between pages
        return false;
    }
}

其次,一定要使用正规ViewPager,你可能会指定为android.support.v4.view.ViewPager这个类来代替。在您的排版文件,你要的东西,如指定:

Next, make sure to use this class instead of the regular ViewPager, which you probably specified as android.support.v4.view.ViewPager. In your layout file, you'll want to specify it with something like:

<com.yourcompany.NonSwipeableViewPager
    android:id="@+id/view_pager"
    android:layout_width="match_parent"
    android:layout_height="0dp"
    android:layout_weight="1" />

这特殊的例子是在一个LinearLayout中,其目的是占据整个屏幕,这就是为什么layout_weight为1,layout_height是0dp。

This particular example is in a LinearLayout and is meant to take up the entire screen, which is why layout_weight is 1 and layout_height is 0dp.

这篇关于通过用手指在ViewPager刷卡如何禁用分页,但仍然可以刷卡编程?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆