May be duplicate of:
- Intercepting touch events in ViewPagerIndicator
- Disabling & Enabling Paging In ViewPager in Android
- android: ViewPager and HorizontalScrollVIew
I am using ViewPagerIndicator in my android app for swiping dynamic number of view and its working fine.
What is want? When user click on one of the slide its corresponding view will open. But i am unable to override touch event on Pager.
Activity code is :
public class MainActivity extends BaseSampleActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mAdapter = new TestFragmentAdapter(getSupportFragmentManager());
mPager = (ViewPager)findViewById(R.id.pager);
mPager.setAdapter(mAdapter);
mPager.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
// TODO Auto-generated method stub
System.out.print(event.getAction());//not working
return false;
}
});
mIndicator = (CirclePageIndicator)findViewById(R.id.indicator);
mIndicator.setViewPager(mPager);
}
}
I have searched a lot but didn't found proper solution. But haven't got proper and brief answer
I also had a same issue. First I created a CustomViewPager
, which extends ViewPager
:
and override onTouch
and onInterceptTouch
events:
public class CustomViewPager extends ViewPager {
public CustomViewPager(Context context, AttributeSet attrs) {
super(context, attrs);
}
@Override
public boolean onInterceptTouchEvent(MotionEvent event) {
return super.onInterceptTouchEvent(event);
}
@Override
public boolean onTouchEvent(MotionEvent event){
return super.onTountEvent(event);
}
}
Your xml should be:
<android.support.v4.view.ViewPager
android:id="@+id/pager"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="7" />
Change it to
<com.yourpackage.CustomViewPager
android:id="@+id/pager"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="7" />
For click event use GestureDetector
. Sending MotionEvent
to the tapGestureDetector.
tapGestureDetector = new GestureDetector(this, new TapGestureListener());
viewPager.setOnTouchListener(new OnTouchListener() {
public boolean onTouch(View v, MotionEvent event) {
tapGestureDetector.onTouchEvent(event);
return false;
}
});
If you are using the compatibility library, you can change the first line to:
tapGestureDetector = new GestureDetectorCompat(this, new TapGestureListener());
You can handle your Event in the GestureListener:
class TapGestureListener extends GestureDetector.SimpleOnGestureListener{
@Override
public boolean onSingleTapConfirmed(MotionEvent e) {
// Your Code here
}
}
来源:https://stackoverflow.com/questions/22961427/touch-or-click-event-viewpagerindicator-in-android