onClick on ViewPager not triggered

后端 未结 8 1138
有刺的猬
有刺的猬 2020-11-28 04:49

I set a click listener on a ViewPager, but the onClick event is never called. I guess the touch event detection of the ViewPager is interfering, bu

相关标签:
8条回答
  • 2020-11-28 05:42

    Make sure that one of the unintended views inside the page is not consuming click event. I had an issue where android:clickable was true on the image view and I could not get click event from its parent. After removing that android:clickable from image view, the click events are sent to its parent (BannerView) now. See the example code

    public ViewPagerAdapter extends PagerAdapter {
    ...
    
    public Object instantiateItem (ViewGroup container, int position) {
    
        MyItem item = this.myItems.get(position);
    
        BannerView bannerView = new BannerView(container.getContext());
        ImageView imageView = (ImageView) bannerView.findViewById(R.id.header_image);
    
        this.setupClickListener(bannerView, position);
    
         container.addView(bannerView);
         return bannerView;
    }
    
    private void setupClickListener(final BannerView view, final int position) {
    
        view.setOnClickListener(new OnClickListener() {
    
                @Override
                public void onClick(View v) {
    
                   // Page is clicked!
                   MyItem item = ViewPagerAdapter.this.myItems.get(position);
                   ViewPagerAdapter.this.showNextActivity(view.getContext(), item);               
                }
         });
    
    }
    

    }

    0 讨论(0)
  • 2020-11-28 05:44

    I know it's kinda old topic but I think this is much easier solution.

    ViewPager viewPager = new ViewPager(this);
    viewPager.setAdapter(yourPagerAdapter);
    
    // somewhere where you setup your viewPager add this
    viewPager.setOnTouchListener(
        new View.OnTouchListener() {
            private boolean moved;
    
            @Override
            public boolean onTouch(View view, MotionEvent motionEvent) {
                if (motionEvent.getAction() == MotionEvent.ACTION_DOWN) {
                    moved = false;
                }
                if (motionEvent.getAction() == MotionEvent.ACTION_MOVE) {
                    moved = true;
                }
                if (motionEvent.getAction() == MotionEvent.ACTION_UP) {
                    if (!moved) {
                        view.performClick();
                    }
                }
    
                return false;
            }
        }
    );
    
    // then you can simply use the standard onClickListener ...
    viewPager.setOnClickListener(
        new View.OnClickListener() {
    
            @Override
            public void onClick(View view) {
                Log.i(LOG, "Dayum!");
            }
        }
    );
    
    0 讨论(0)
提交回复
热议问题