Reputation: 6132
I currently have an application for my phone which uses a tab navigation actionbar to navigate between three fragments.
I now want to create a tablet equivalent of this app, but instead of using the actionbar, I want the three fragments living next to each other. So each fragment would fill up 1/3th of the screen.
The problem is, I can't figure out how to approach this. I've thought of using the Design part of Android Studio to create placeholders, then use the onCreate()
method to fill those placeholders by inflating the fragments in it. But I still have no idea on how to approach this.
Does anyone have any ideas?
Upvotes: 1
Views: 3504
Reputation: 1360
Your idea to use onCreate() is good.
Basically all you need is a container of type ViewGroup foreach of your fragments and then use FragmentTransactions to add them accordingly.
Consider this:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.yourlayout);
// Create fragments
Fragment f0 = new Fragment0();
Fragment f1 = new Fragment1();
Fragment f2 = new Fragment2();
// Add fragments
FragmentManager fm = getFragmentManager();
FragmentTransaction ft = fm.beginTransaction();
ft.add(R.id.container0, f0);
ft.add(R.id.container1, f1);
ft.add(R.id.container2, f2);
ft.commit();
}
See this for more examples and background information: http://www.survivingwithandroid.com/2013/04/android-fragment-transaction.html
Upvotes: 1
Reputation: 1210
You can make 3 placeholders each taking one third of the screen and then fill them in with fragments. Of course you have to make those only in layout for tablets.
Fragment fragment1 = new FirstFragment();
Fragment fragment2 = new SecondFragment();
Fragment fragment3 = new ThirdFragment();
getSupportFragmentManager()
.beginTransaction()
.replace(R.id.placeholder1, fragment1)
.replace(R.id.placeholder2, fragment2)
.replace(R.id.placeholder3, fragment3)
.commit();
EDIT: Example of layout
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal">
<FrameLayout
android:id="@+id/placeholder1"
android:layout_weight="1"
android:layout_width="0dp"
android:layout_height="match_parent"/>
<FrameLayout
android:id="@+id/placeholder2"
android:layout_weight="1"
android:layout_width="0dp"
android:layout_height="match_parent"/>
<FrameLayout
android:id="@+id/placeholder3"
android:layout_weight="1"
android:layout_width="0dp"
android:layout_height="match_parent"/>
</LinearLayout>
Upvotes: 3