public static class ExampleFragment extends Fragment{
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
return inflater.inflate(R.layout.hello_world, container, false);
}
}
Estático
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<fragment android:name="com.example.android.fragments.HeadlinesFragment"
android:id="@+id/headlines_fragment"
android:layout_weight="1"
android:layout_width="0dp"
android:layout_height="match_parent" />
<fragment android:name="com.example.android.fragments.ArticleFragment"
android:id="@+id/article_fragment"
android:layout_weight="2"
android:layout_width="0dp"
android:layout_height="match_parent" />
</LinearLayout>
Fragment fragment = getFragmentManager().findFragmentById( R.id.static_fragment );
Al añadir fragments de este modo, no se pueden eliminar en runtime.
Dinámico
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<FrameLayout
android:id="@+id/fragment_container"
android:layout_weight="1"
android:layout_width="0dp"
android:layout_height="match_parent" />
<FrameLayout
android:id="@+id/fragment_container2"
android:layout_weight="1"
android:layout_width="0dp"
android:layout_height="match_parent" />
</LinearLayout>
Podemos usar FrameLayouts e inflar los fragments más tarde.
Dinámico
getSupportFragmentManager().beginTransaction()
.add(R.id.fragment_container, firstFragment).commit();
getSupportFragmentManager().beginTransaction()
.replace(R.id.element, firstFragment).commit();
Remplazando otro elemento
public class HeadlinesFragment extends Fragment {
OnHeadlineSelectedListener mCallback;
//La activity ha de implementar esta interface
public interface OnHeadlineSelectedListener {
public void onArticleSelected(int position);
}
@Override
public void onAttach(Activity activity) {
super.onAttach(activity);
// Nos aseguramos que la activity implementa la interface
try {
mCallback = (OnHeadlineSelectedListener) activity;
} catch (ClassCastException e) {
throw new ClassCastException(activity.toString()
+ " must implement OnHeadlineSelectedListener");
}
//podemos llamarlo para comunicarnos con la activity
mCallback.onArticleSelected(pos);
}
}