Reputation: 121
I recently modified my ActionBar as to have two tabs, corresponding to two Fragments respectively.
Let's say my first tab is the Main Page, the second my About Page.
The About Page is static.
The Main Page changes. Let's say, for question's sake, that the Main Page has this single button in the center of the screen. I want it in such a way that when the user clicks the button, the page changes to another screen with text. This is easily done with Activities using Intent. I don't know how to do this with Fragments.
In sum, what is the best practice switching Fragments inside a tab?
Upvotes: 0
Views: 215
Reputation: 2210
Consider using fragment's method getChildFragmentManager().
So your way to go.
In you first tab
Create nested fragment whitch will display button.
MainPage.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:orientation="horizontal" >
<FrameLayout
android:id="@+id/fragment_container"
android:layout_width="wrap_content"
android:layout_height="match_parent"
/>
</LinearLayout>
class MainPage extends Fragment(){
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
FragmentTransaction ft = getChildFragmentManager().beginTransaction();
ft.replace(R.id.fragment_container, new ButtonFragment(), ButtonFragment.class.getName());
ft.commit();
((Button)getActivity().findViewById(R.id.your_button)).setOnClickListener(new OnClickListener(){
public void onClick(View v){
FragmentTransaction ft = getChildFragmentManager().beginTransaction();
ft.replace(R.id.fragment_container, new TextFragment(), TextFragment.class.getName());
ft.addToBackStack(TextFragment.class.getName());
ft.commit();
}
})
}
public boolean onBackPressed(){
FragmentManager mn = getChildFragmentManager();
if(mn.getBackStackEntryCount()>0)
mn.popBackStack(man.getBackStackEntryAt(0).getName(), FragmentManager.POP_BACK_STACK_INCLUSIVE);
}
class ButtonFragment extends Fragment(){
.....
public void onCreateView(Bundle savedinstance){
//inflate you view with button here
}
Upvotes: 1