baldguy
baldguy

Reputation: 2082

Get back to first fragment of view pager when clicked on button in second fragment of view pager

I am using view pager and in that I am having three fragments. In my second fragment I am having button clicking on which take you to the first fragment.

I am new with the fragment. So please give me your valuable suggestions and links for this.

Thanking you in advance.

Upvotes: 1

Views: 888

Answers (1)

Mukesh Soni
Mukesh Soni

Reputation: 6668

On click of the button in the second fragment, communicate from your fragment to your parent activity that the first fragment is to be shown. You parent activity can then call a function in your view pager which shows the first fragment.

Define an interface in the fragment -

OnCategorySelectedListener mCallback;
 // Container Activity must implement this interface. 
    public interface OnBackSelectedListener {
        // Called when the user clicks back button
        public void onBackSelected();
    }

In onAttach(), link the callback -

try {
            mCallback = (OnBackSelectedListener) activity;
        } catch (ClassCastException e) {
            throw new ClassCastException(activity.toString()
                    + " must implement OnBackSelectedListener");
        }

When the back button is clicked, call the callback interface method -

mCallback.onBackSelected();

In your view pager, implement the onBackSelectedListener interface.

Upvotes: 2

Related Questions