Switching Between Fragments In A Single Activity
Solution 1:
I create this main layout:
<LinearLayoutxmlns: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="horizontal"tools:context="com.example.fragmentsexample.MainActivity" ><FrameLayoutandroid:id="@+id/contentFragment"android:layout_width="fill_parent"android:layout_height="fill_parent"android:layout_weight="1" /></LinearLayout>
And I replenished in the FrameActivity with:
@OverridepublicvoidonCreate(Bundle savedInstanceState) {
...
Fragmentfragment=newDashboard();
FragmentManagerfm= getSupportFragmentManager();
FragmentTransactiontransaction= fm.beginTransaction();
transaction.replace(R.id.contentFragment, fragment);
transaction.commit();
...
}
And I repleace on onClick Method with the same code, changing Fragment (Dashboard for Events):
@Overridepublicvoid onClick.... {
...
Fragmentfragment=newEvents();
FragmentManagerfm= getSupportFragmentManager();
FragmentTransactiontransaction= fm.beginTransaction();
transaction.replace(R.id.contentFragment, fragment); //Container -> R.id.contentFragment
transaction.commit();
...
}
Solution 2:
Personally, I would not have any <fragment>
elements.
Step #1: Populate your activity layout with a <FrameLayout>
for the variable piece of the wizard, plus your various buttons.
Step #2: In onCreate()
of the activity, run a FragmentTransaction
to load the first wizard page into the FrameLayout
.
Step #3: On the "next" click, run a FragmentTransaction
to replace the contents of the FrameLayout
with the next page of the wizard.
Step #4: Add in the appropriate smarts for disabling the buttons when they are unusable (e.g., back on the first wizard page).
Also, you will want to think about how the BACK button should work in conjunction with any on-screen "back" button in the wizard. If you want them to both behave identically, you will need to add each transaction to the back stack and pop stuff off the back stack when you handle the "back" button.
Someday, if nobody beats me to it, I'll try to create a wizard-by-way-of-fragments example, or perhaps a reusable component.
Solution 3:
Another option is to use the Android-WizardPager by Roman Nurik.
Key features:
- Branching, or the ability for wizard steps to influence the availability of later steps
- Allowing the user to review before committing
- Allowing the user freeform navigation between wizard steps
- Support for required and optional steps
- Support for step classes (technically, each step is an instance of a Java class, so you can have multiple instances within the wizard)
More info here.
Post a Comment for "Switching Between Fragments In A Single Activity"