I want to set on click event in my View Pager. My ViewPagerAdapter
looks like this-
public class ViewPagerAdapder extends PagerAdapter {
Activity activity;
String image[];
public ViewPagerAdapder(Activity act, String[] imgArra) {
image = imgArra;
activity = act;
}
public int getCount() {
return image.length;
}
public Object instantiateItem(View collection, final int position) {
ImageView view = new ImageView(activity);
view.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
ViewGroup.LayoutParams.MATCH_PARENT));
new ImageDownloaderTask(view).execute(image[position]);
view.setScaleType(ImageView.ScaleType.CENTER_CROP);
view.setAdjustViewBounds(true);
((ViewPager) collection).addView(view, 0);
// view.setBackgroundResource(imageArray[position]);
return view;
}
@Override
public void destroyItem(View arg0, int arg1, Object arg2) {
((ViewPager) arg0).removeView((View) arg2);
}
@Override
public boolean isViewFromObject(View arg0, Object arg1) {
return arg0 == ((View) arg1);
}
@Override
public Parcelable saveState() {
return null;
}
}
And I am setting OnClickListener
like this in my Main Activity
myPager = (ViewPager) view.findViewById(R.id.viewpager);
myPager.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Toast.makeText(getActivity(), "Ckecking Success",
Toast.LENGTH_SHORT).show();
}
}
My ViewPager works fine. I tried to implement OnClickListener in both Main Activity as well as in the ViewPagerAdapter class. It does not work either way.
Use this class for view pager click.
ClickableViewPager.java
public class ClickableViewPager extends ViewPager {
private OnItemClickListener mOnItemClickListener;
public ClickableViewPager(Context context) {
super(context);
setup();
}
public ClickableViewPager(Context context, AttributeSet attrs) {
super(context, attrs);
setup();
}
private void setup() {
final GestureDetector tapGestureDetector = new GestureDetector(getContext(), new TapGestureListener());
setOnTouchListener(new OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
tapGestureDetector.onTouchEvent(event);
return false;
}
});
}
public void setOnItemClickListener(OnItemClickListener onItemClickListener) {
mOnItemClickListener = onItemClickListener;
}
public interface OnItemClickListener {
void onItemClick(int position);
}
private class TapGestureListener extends GestureDetector.SimpleOnGestureListener {
@Override
public boolean onSingleTapConfirmed(MotionEvent e) {
if(mOnItemClickListener != null) {
mOnItemClickListener.onItemClick(getCurrentItem());
}
return true;
}
}
}
Click event
clickablePager.setOnItemClickListener(new ClickableViewPager.OnItemClickListener() {
@Override
public void onItemClick(int position) {
}
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With