Reputation: 2646
I am trying to switch between fragments on my activity. I was reading this tutorial, but my case is a bit different since I don't want/can't use the 'FragmentPagerAdapter', instead, I want that a button that is pressed on activity will switch between 2 fragments.
My activity layout consist of a Button and ViewPager. in Addition I have got Fragment1 and Fragment2. How can I switch between this fragments using OnClick method?
My Layout:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<Button
android:text="Switch it"
android:onClick="switchFragment"/>
<android.support.v4.view.ViewPager
android:id="@+id/pager"
android:layout_width="match_parent"
android:layout_height="match_parent">
</android.support.v4.view.ViewPager>
</LinearLayout>
and my activity:
public class MainHeaderFragment2 extends ActionBarActivity {
...
public void switchFragment(View view){
Fragment fragment
if(checkSomething())
fragment = new Fragment1();
else
fragment = new Fragment2();
ViewPager viewPager = (ViewPager) findViewById(R.id.pager);
// now need to put the selected fragment in ViewPager somehow.
// How? that is my question
}
}
Upvotes: 1
Views: 1306
Reputation: 20023
Based on your comments, this is what you should do:
Change your layout to this:
<Button
android:text="Switch it"
android:onClick="switchFragment"/>
<FrameLayout
android:id="@+id/fragment_container"
android:layout_width="match_parent"
android:layout_height="match_parent" />
To populate it first time with your first fragment:
Fragment1 fragment1 = Fragment1.create();
FragmentManager manager = getSupportFragmentManager();
FragmentTransaction fragmentTransaction = manager.beginTransaction();
fragmentTransaction.add(R.id.fragment_container, fragment1);
fragmentTransaction.commit();
To replace it,
Fragment2 fragment2 = Fragment2.create();
FragmentManager manager = getSupportFragmentManager();
FragmentTransaction fragmentTransaction = manager.beginTransaction();
fragmentTransaction.replace(R.id.fragment_container, fragment2, "optionalTag");
fragmentTransaction.commit();
Fragmen1
and Fragment2
are the fragments you want to display or replace.
Upvotes: 1