Android: Viewpager and Horizontalscrollview

Scrolling behaviour: HorizontalScrollView inside ViewPager

1.Extend ViewPager Class:

public class ViewPagerContainingHorizontalScrollView extends ViewPager {
private Float x_old;
private boolean bDoIntercept = false;
private boolean bHsvRightEdge = false;
private boolean bHsvLeftEdge = true;

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

private float calculateDistanceSwipe(MotionEvent ev){
float distance = 0;
if (x_old == null) {
x_old = ev.getX();
} else {
distance = ev.getX() - x_old;
x_old = null;
}
return distance;
}

@Override
public boolean dispatchTouchEvent(MotionEvent ev) {
mDoIntercept = false;
if(ev.getAction() == MotionEvent.ACTION_MOVE) {
float distance = calculateDistanceSwipe(ev);

if (distance < 0) {//scrolling left direction
if (bHsvRightEdge) { //HSV right edge
bDoIntercept = true;
//When scrolling slow VP may not switch page.
//Then HSV snaps back into old position.
//To allow HSV to scroll into non blocked direction set following to false.
bHsvRightEdge = false;
}
bHsvLeftEdge = false;//scrolling left means left edge not reached
} else if (distance > 0) {//scrolling right direction
if (bHsvLeftEdge) { //HSV left edge
bDoIntercept = true;
//When scrolling slow VP may not switch page.
//Then HSV snaps back into old position.
//To allow HSV to scroll into non blocked direction set following to false.
bHsvLeftEdge = false;
}
bHsvRightEdge = false;//scrolling right means right edge not reached
}
}
return super.dispatchTouchEvent(ev);
}

@Override
public boolean onInterceptTouchEvent(MotionEvent ev) {
if(bDoIntercept){
return true;
}else{
return super.onInterceptTouchEvent(ev);
}
}

@Override
protected boolean canScroll(View v, boolean checkV, int dx, int x, int y) {
if (v instanceof HorizontalScrollView) {
HorizontalScrollView hsv = (HorizontalScrollView) v;
int max_scrollX = hsv.getChildAt(0).getWidth() - hsv.getWidth();
int min_scrollX = 0;
int current_scroll_x = hsv.getScrollX();

if (current_scroll_x == max_scrollX) { //HSV right edge
bHsvRightEdge = true;
}

if (current_scroll_x == min_scrollX) { //HSV left edge
bHsvLeftEdge = true;
}
return true;
}
return super.canScroll(v, checkV, dx, x, y);
}
}

  1. Use this custom VP in XML.
  2. Enjoy nested HSV scrolling in VP :-)

Touch Event Mechanism Overview for this specific case

ViewPager2 with horizontal scrollView inside

I find a solution it's a know bug as you can see here https://issuetracker.google.com/issues/123006042 maybe they would solve it in the next updates

Thanks to TakeInfos and the exemple project inside the link

 recyclerViewPicture.addOnItemTouchListener(new RecyclerView.OnItemTouchListener() {
int lastX = 0;
@Override
public boolean onInterceptTouchEvent(@NonNull RecyclerView rv, @NonNull MotionEvent e) {
switch (e.getAction()) {
case MotionEvent.ACTION_DOWN:
lastX = (int) e.getX();
break;
case MotionEvent.ACTION_MOVE:
boolean isScrollingRight = e.getX() < lastX;
if ((isScrollingRight && ((LinearLayoutManager) recyclerViewPicture.getLayoutManager()).findLastCompletelyVisibleItemPosition() == recyclerViewPicture.getAdapter().getItemCount() - 1) ||
(!isScrollingRight && ((LinearLayoutManager) recyclerViewPicture.getLayoutManager()).findFirstCompletelyVisibleItemPosition() == 0)) {
viewPager.setUserInputEnabled(true);
} else {
viewPager.setUserInputEnabled(false);
}
break;
case MotionEvent.ACTION_UP:
lastX = 0;
viewPager.setUserInputEnabled(true);
break;
}
return false;
}

@Override
public void onTouchEvent(@NonNull RecyclerView rv, @NonNull MotionEvent e) {
}

@Override
public void onRequestDisallowInterceptTouchEvent(boolean disallowIntercept) {

}
});

I'm checking if the user scroll on the right or on the left. If the user reach the end or the start of the recyclerView I'm enable or disable the swipe on the view pager

horizontalscrollview inside viewpager

In the end I made a custom pager and overrided the method canScroll like so

@Override
protected boolean canScroll(View v, boolean checkV, int dx, int x, int y) {
if (v instanceof HorizontalScrollView) {
HorizontalScrollView scroll = (HorizontalScrollView) v;

int vScrollX = scroll.getScrollX();
TableLayout table = (TableLayout) scroll.getChildAt(scroll
.getChildCount() - 1);
int diff = (table.getRight() - (scroll.getWidth()
+ scroll.getScrollX() + table.getLeft()));

if (vScrollX == 0 && diff <= 0) {// table without scroll
if (dx > 20 && this.getCurrentItem() > 0) {
this.setCurrentItem(this.getCurrentItem() - 1, true);
} else if (dx < -20
&& this.getCurrentItem() + 1 < this.getChildCount()) {
this.setCurrentItem(this.getCurrentItem() + 1, true);
}
return false; // change page
}
if (vScrollX == 0 && dx > 20) {// left edge, swiping right
if (this.getCurrentItem() > 0) {
this.setCurrentItem(this.getCurrentItem() - 1, true);
}
return false; // change page
}
if (vScrollX == 0 && dx < -20) {// left edge, swiping left
return true;// scroll
}
if (diff <= 0 && dx > 20) {// right edge, swiping right
return true;// scroll
}
if (diff <= 0 && dx < -20) {// right edge, swiping left
if (this.getCurrentItem() + 1 < this.getChildCount()) {
this.setCurrentItem(this.getCurrentItem() + 1, true);
}
return false;// change page
}
}
return super.canScroll(v, checkV, dx, x, y);
}

Actions of HorizontalScrollView inside ViewPager

implementing onTouch and onClick will consume the touch event by onTouch and consider it consumed and not pass it on to the other various touch handlers which make your onClickListener useless.
the Documentation:

onTouch() - This returns a boolean to indicate whether your listener consumes this event. The important thing is that this event can have multiple actions that follow each other. So, if you return false when the down action event is received, you indicate that you have not consumed the event and are also not interested in subsequent actions from this event. Thus, you will not be called for any other actions within the event, such as a finger gesture, or the eventual up action event.

here is some of the available solutions to handle this situation:

1-you can use onToach and onClick as an inner classes instead of implementing each listener.

2- you can use onToach to detect a tab event:

if (gestureDetector.onTouchEvent(arg)) {
// single tap
return true;
} else {
// action up or down code
}

Design a HorizontalScrollView inside of ViewPager or use fragments:

I think this should be tackled with a Non Swipeable ViewPager. There is no way the view pager and the underlying Fragments should respond to the swiping gesture. The methods to override to disable swiping within the ViewPager are:

  1. onTouchEvent() - returns false.
  2. onInterceptTouchEvent()- returns false.

Refer to this SO question for more information on how to achieve this.

Next up you want to be using Fragments within each of your pager holders. So we're building the following layout:

Sample Image

Within the parent activity a FragmentPagerAdapter is instantiated and your tabs added with a tag:

Activity changes

@Override
protected void onCreate(final Bundle saveInstanceState) {
final FragmentPagerAdapter myTabAdapter = new MyFragmentPagerAdapter(
<Your ViewPager View>, <Your activity context, this>);
myTabAdapter.addTab(getActionBar().newTab(), "YOUR TAG", "Your Title");
// etc...
}

So this gives us the frame of the diagram above. A hosting activity, containing a ViewPager and the underlying tabs. Next up is getting the Fragments (containing your tables) into each of the respective tabs. This is handled by the FragmentPagerAdapter implementation:

Fragment adapter (inner class to activity):

private class MyFragmentPagerAdapter extends FragmentPagerAdapter implements
ActionBar.TabListener, ViewPager.OnPageChangeListener {

/**
* Constructs a pager adapter to back a {@link ViewPager}.
*
* @param pager
* The {@link ViewPager} widget.
* @param activityContext
* The context the widget is being added under.
*/
public SpotMenuFragmentPagerAdapter(final ViewPager pager,
final Context activityContext) {
super(getFragmentManager());
pager.setAdapter(this);
this.context = activityContext;
}

/**
* Adds a tab to the hosting activity action bar.
*
* @param newTab
* The tab to add.
* @param tag
* The tab tag for id purposes.
* @param label
* The label of the tab displayed to the user.
*/
public void addTab(final ActionBar.Tab newTab, final String tag,
final String label) {
newTab.setTag(tag);
newTab.setText(label);
newTab.setTabListener(this);
getSupportActionBar().addTab(newTab);
}

/**
* This is where you do the work of building the correct fragment based
* on the tab currently selected.
*
* @see FragmentPagerAdapter#getItem(int)
*/
@Override
public Fragment getItem(final int position) {
final Tab tab = getActionBar().getTabAt(position);
if ("MY TAG".equals(tab.getTag().toString()) {
// instantiate the fragment (table) for "MY TAG"
} else {
// instantiate something else...
}
}

/**
* One fragment per tab.
*
* @see android.support.v4.view.PagerAdapter#getCount()
*/
@Override
public int getCount() {
return getSupportActionBar().getTabCount();
}

/**
* @see ViewPager.OnPageChangeListener#onPageScrollStateChanged(int)
*/
@Override
public void onPageScrollStateChanged(final int arg0) {
// No-op.
}

/**
* @see ViewPager.OnPageChangeListener#onPageScrolled(int, float, int)
*/
@Override
public void onPageScrolled(final int arg0, final float arg1,
final int arg2) {
// No-op.
}

/**
* @see ViewPager.OnPageChangeListener#onPageSelected(int)
*/
@Override
public void onPageSelected(final int position) {
getSupportActionBar().setSelectedNavigationItem(position);
}

/**
* @see TabListener#onTabSelected(app.ActionBar.Tab,
* app.FragmentTransaction)
*/
@Override
public void onTabSelected(final Tab tab, final FragmentTransaction ft) {
viewPager.setCurrentItem(tab.getPosition());
}

/**
* @see TabListener#onTabUnselected(ActionBar.Tab,
* app.FragmentTransaction)
*/
@Override
public void onTabUnselected(final Tab tab, final FragmentTransaction ft) {
// No-op.
}

/**
* @see TabListener#onTabReselected(ActionBar.Tab,app.FragmentTransaction)
*/
@Override
public void onTabReselected(final Tab tab, final FragmentTransaction ft) {
// No-op.
}
}

So hopefully by this point we have an activity hosting a 'non-swipeable' view pager and a mechanism for switching tabs in the form of the tab bar underneath the title (or alongside depending on the screen size). From this point I am sure you could customise to replace the tab bar with some navigational arrows.

Note: A lot of that was written from memory but hopefully I've conveyed the gist of where I would go with this.

Update

In response to the updated question: you can set the tab to be any old view. Set the TabSpec accordingly. Apologies I haven't used this myself.

HorizontalScrollView in View Pager

The following is a complete example of how to implement a ViewPager with different fragment Types and different layout files.

Try This



Related Topics



Leave a reply



Submit