How do I validate before selecting a new tab or selecting a new snippet using Swipe tabs in Android?

I have 4 tabs. But before allowing the user to navigate to another tab using the Scroll or Tab function, I want to do all of the checks related to the snippet that is attached to the current tab. How can I achieve this?

Now that the action bar tab listener is deprecated, what methods can you use to do this?

+3


source to share


1 answer


One way to do this is in your TabsPagerAdapter

, in your method getItemPosition

.

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

      

Then you can define an interface for the ValidateFragment

public interface ValidateFragment {
    public void validate();
}

      

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

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

}

      

Another way you can do this is by using a method setUserVisibleHint

that gets called every time 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 scroll if fragment

not checked, I think you should implement your own class ViewPager

and override onInterceptTouchEvent

and onTouchEvent

if the phrase is 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;
}

      

Alternatively, you can try using a method of setOnTouchListener

yours ViewPager

in yours Activity

and add similar logic to what you have in your actionbar tab listener

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

      

This SO question will be helpful for implementing both.

+1


source







All Articles