gunesevitan
gunesevitan

Reputation: 965

How to use Button to switch fragments in a ViewPager?

I have 3 main fragments inside viewpager and they have couple of buttons. I want each button to navigate to another fragment and back button to get back to main fragment. I tried to add fragment transaction but it does not work. What am I doing wrong here?

this is one of the main fragments

public class OneFragment extends Fragment implements View.OnClickListener{


    public OneFragment() {

    }


    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {

        return inflater.inflate(R.layout.fragment_one, container, false);
    }


    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.aButton:
                FragmentManager manager = getFragmentManager();
                FragmentTransaction transaction = manager.beginTransaction();
                transaction.replace(R.id.fragment_one, AFragment.newInstance()); 
                transaction.commit();
                break;
        }
    }
}

this is the fragment I want to navigate

public class AFragment extends Fragment{

    public AFragment() {

    }
    public static AFragment newInstance() {
        AFragment fragment = new AFragment();
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);


    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {

        return inflater.inflate(R.layout.a_fragment, container, false);
    }

}

Upvotes: 1

Views: 1853

Answers (1)

Daniel Nugent
Daniel Nugent

Reputation: 43322

First, define a public method in your Activity to switch tabs in the ViewPager, and also define the onBackPressed() override, which will select the first index when the back button is pressed:

public void selectIndex(int newIndex) {
  mViewPager.setCurrentItem(newIndex);
}

@Override
public void onBackPressed() {
  int currentPosition = mViewPager.getCurrentItem();
  if (currentPosition != 0) {
        mViewPager.setCurrentItem(0);
  } else {
    super.onBackPressed();
  }
}

Then, modify the click listener in the Fragment in order to call the selectIndex() method:

@Override
public void onClick(View v) {
    switch (v.getId()){
        case R.id.aButton:
            //select the index of AFragment:
            ((MainActivity)getActivity()).selectIndex(1);
            break;
    }
}

Upvotes: 5

Related Questions