3

I Have 4 tabs. But before allowing the user to move on to the other tab using Swiping or tab pressing, I want to perform all validations relating to the fragment attached with the current tab. How can I achieve that?

Now that Action Bar Tab Listener is deprecated, what are methods can be used to do this?

arlistan
  • 731
  • 9
  • 20
seetha
  • 57
  • 7

1 Answers1

1

One way of doing it is in your TabsPagerAdapter, in your getItemPosition method.

@Override
public int getItemPosition(Object object) {
    if (object instanceof ValidatedFragment) {
        ((ValidatedFragment) object).validate();
    }
    return super.getItemPosition(object);
}

Then you can define an interface for ValidateFragment

public interface ValidateFragment {
    public void validate();
}

And finally, your fragment can extend ValidateFragment and implement the validation:

YouFragment implements ValidateFragment {
....
@override
public void validate(){
    //Do your validation here
}
...

}

Another way you can do it, is by using the method setUserVisibleHint, that gets called everytime your fragment is visible:

 @Override
public void setUserVisibleHint(boolean isVisibleToUser) {
    super.setUserVisibleHint(isVisibleToUser);
    if (isVisibleToUser) {
        //Do your validation here
    }
}

Edit:
if you don't want the user to be able to swipe if the fragment is not validated, I think you should implement your own ViewPager class, and override onInterceptTouchEvent and onTouchEvent if the frags are not validated.

@Override
public boolean onInterceptTouchEvent(MotionEvent arg0) {
    //Validate here and return false if the user shouldn't be able to swipe
    return false;
}

@Override
public boolean onTouchEvent(MotionEvent event) {
    //Validate here and return false if the user shouldn't be able to swipe
    return false;
}

Also, you can try to use the setOnTouchListener method of your ViewPager in your Activity, and add a similar logic to what your currently have on your Action Bar Tab Listener

mPager.setOnTouchListener(new OnTouchListener()
{           
    @Override
    public boolean onTouch(View v, MotionEvent event)
    {
        return true;
    }
});

This SO question will be usefull for implementing both options.

Community
  • 1
  • 1
arlistan
  • 731
  • 9
  • 20
  • Thanks Fede. I want the validation for a particular page to happen before I move on to the other tabs. Fear second approach might not work. – seetha Nov 06 '14 at 03:37
  • GetitemPosition approach - Let the user try to swipe or press other tabs, but the validation should happen before showing him the desired fragement. He should not move out of the current fragment if he has not done the validation. Will this help. – seetha Nov 06 '14 at 03:39
  • I added a new option for you to try to implement – arlistan Nov 06 '14 at 13:56