如何禁用用手指触摸滑动的ViewPager扩展Android中的PagerAdapter

时间:2019-09-07 06:05:28

标签: android-viewpager touch swipe touch-event android-pageradapter

我有带有查看寻呼机的滑块。我有适配器扩展PagerAdapter。 问题是:我不想用手指滑动滑块。这意味着,我希望它能够自动运行。

public class TopFoodSlider_adapter extends PagerAdapter {

    private Context context;
    private List<top_food_slider> slideList;
    private int custom_postion = 0;
    private int t =0;

    public TopFoodSlider_adapter(Context context, List<top_food_slider> slideList) {
        this.context = context;
        this.slideList = slideList;
    }



    @Override
    public int getCount() {
        return Integer.MAX_VALUE;
    }

    @Override
    public boolean isViewFromObject(@NonNull View view, @NonNull Object object) {
        return (view == object);
    }

    @NonNull
    @Override
    public Object instantiateItem(@NonNull ViewGroup container, int position)
    {
        LayoutInflater layoutInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        View view = layoutInflater.inflate(R.layout.top_food_slider_item,container,false);

        top_food_slider slid = slideList.get(custom_postion);
        custom_postion++;
        int img=slid.getImg_src();
        ImageView imageView=view.findViewById(R.id.imageView);

        imageView.setImageResource(img);
        container.addView(view);

        if (custom_postion>=slideList.size())
            custom_postion = 0;

        return view;
    }

    @Override
    public void destroyItem(@NonNull ViewGroup container, int position, @NonNull Object object) {
        container.removeView((LinearLayout)object);
    }

}

1 个答案:

答案 0 :(得分:0)

您可以通过扩展StoryViewPager并覆盖onTouchEventonInterceptTouchEvent来禁用滑动。

class NoSwipingViewPager @JvmOverloads constructor(
    context: Context,
    attrs: AttributeSet? = null
) : ViewPager(context, attrs) {

    override fun onTouchEvent(event: MotionEvent): Boolean {
        return false

    }

    override fun onInterceptTouchEvent(event: MotionEvent): Boolean {
        return  false
    }
}

您可以在以下答案中进一步了解它:How do disable paging by swiping with finger in ViewPager but still be able to swipe programmatically?

我希望这会有所帮助!