- Create the fragments' layout
ex.
fragment A with red background - layout/A.xml
fragment B with green background - layout/B.xml - Create the classes of fragments to add UI
public static class fragmentA extends Fragment { @Override public View onCreateView( LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // Inflate the layout for this fragment return inflater.inflate(R.layout.<fragment's layout>, container, false); } }
where <fragment's layout> is the fragment's layout filename. ex. A.xml or B.xml - Add fragment(s) to an activity
- Declare in layout file (XML)
(For large device use,) create another layout file (in directory "layout-large") in which the fragment(s) would be shown. ex. home.xml<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="horizontal" android:layout_width="match_parent" android:layout_height="match_parent"> <fragment android:name="sowhat.practice.fragment.fragmentA" android:id="@+id/list" android:layout_weight="1" android:layout_width="0dp" android:layout_height="match_parent" /> <fragment android:name="sowhat.practice.fragment.fragmentB" android:id="@+id/viewer" android:layout_weight="2" android:layout_width="0dp" android:layout_height="match_parent" /> </LinearLayout>
where android:name specifies the fragment class to instantiate the layout in the form <package>.<class> - Programmatically add the fragment to an existing ViewGroup.
"If your activity allows the fragments to be removed and replaced, you should add the initial fragment(s) to the activity during the activity's onCreate() method."
"the fragment must have a container View in the layout in which the fragment's layout will reside." - Create a layout file with FrameLayout inside
In order to replace one fragment with another, the activity's layout includes an empty FrameLayout that acts as the fragment container. (For small device use,) create another layout file (in directory "layout") in which the fragment would be shown. (the name of this layout file should be the same with the one in layout-large. ie. home.xml) <FrameLayout xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/fragment_container" android:layout_width="match_parent" android:layout_height="match_parent" />
- Set up in onCreate() of MainActivity
public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.news_articles); if (findViewById(R.id.fragment_container) != null) { if (savedInstanceState != null) { return; } fragmentA firstFragment = new FragmentA(); firstFragment.setArguments(getIntent().getExtras()); getSupportFragmentManager().beginTransaction() .add(R.id.fragment_container, firstFragment).commit(); } }
http://developer.android.com/training/basics/fragments/index.html
http://developer.android.com/guide/components/fragments.html
沒有留言:
張貼留言