Search code examples
androidandroid-tabs

How to perform validation before new tab is selected or swiping to a new fragment with Swipe Tabs in Android?


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?


Solution

  • 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.