2

I have a ViewPager and I'm setting OnClickListener to it.

But the ViewPager is not detecting the on click. Whats wrong here ?

Code:

  viewPager = (ViewPager) findViewById(R.id.pager);
    ImagePagerAdapter adapter = new ImagePagerAdapter();
    viewPager.setAdapter(adapter);        

    viewPager.setOnClickListener(new View.OnClickListener() {    
       @Override
       public void onClick(View view) {
            Toast.makeText(getBaseContext(), "view Pager Clicked",  Toast.LENGTH_SHORT).show();
         }

       });
Jas
  • 3,207
  • 2
  • 15
  • 45
Gissipi_453
  • 1,250
  • 1
  • 25
  • 61

3 Answers3

2

You can use setOnClickListener inside the adapter in instantiateItem method. it works for me.

Fabulist
  • 31
  • 3
1

I understand you want to identify touch events on your ViewPager, so that you can trigger an animation that hides your ActionBar. One method requires you create your own subclass of ViewPager and override onInterceptTouchEvent:

public class ABetterViewPager extends ViewPager {

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

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

    @Override
    public boolean onInterceptTouchEvent(MotionEvent ev) {
        //Enter the code here to communicate a touch event
        return super.onInterceptTouchEvent(ev);
    }
}

You will probably need to tailor the above to your specifications. For instance, you may only want to trigger the event once someone starts to move their finger on the screen, in which case you would use:

if (ev.getAction() == MotionEvent.ACTION_MOVE) {
    //User is moving their finger over the screen
}

In respect to communicating the touch event from your ViewPager to wherever it needs to be to fire your ActionBar hiding animation (which I assume is the Activity hosting the ViewPager) then you can use an interface/EventBus.

Also, don't forget to replace the ViewPager in your xml layout file with the full name of your custom class (i.e. com.example.mywidgets.ABetterViewPager, or whatever)

PPartisan
  • 8,173
  • 4
  • 29
  • 48
-3

ViewPager is not made for onClick. It has OnPageChangelistener as below:

mViewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
    @Override
    public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

    }

    @Override
    public void onPageSelected(int position) {
        // this will execute when page will be selected
    }

    @Override
    public void onPageScrollStateChanged(int state) {

    }
});
Ziem
  • 6,579
  • 8
  • 53
  • 86
Narendra Kumar
  • 551
  • 5
  • 16