<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/LinearLayout1"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="horizontal" >
<fragment
android:id="@+id/fragment1"
android:name="com.example.fragmentexampleapp.ExampleListFragment"
android:layout_width="248dp"
android:layout_height="match_parent" />
<fragment
android:id="@+id/fragment2"
android:name="com.example.fragmentexampleapp.ExampleDetailFragment"
android:layout_width="wrap_content"
android:layout_height="match_parent" />
</LinearLayout>
Fragment
public class ExampleDetailFragment extends Fragment {
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
return inflater.inflate(R.layout.detail_fragment,container, false);
}
}
onCreateView()
returning the View that will be embedded in the surrounding ActivityLayoutInflater
loads XML based layouts and creates View hierarchyÜBERARBEITEN !!!! -> List ersetzen mit Fragment
Fragment
s subclasses, e.g. ListFragment
public class ExampleListFragment extends ListFragment {
@Override
public void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
List<String> songs = Arrays.asList("Blur","Metallica","Bosse");
ArrayAdapter<String> bandArray = new ArrayAdapter<String>
(getActivity(), android.R.layout.simple_list_item_1,songs);
setListAdapter(bandArray);
}
}
Fragments exist in three states when started:
Fragment
is visible and runningActivity
is in the foreground and has focus but the Fragment
is still visibleFragment
is not visible but still alive. Either Activity
has been stopped or
Fragment
removedThe lifecycle of the Activity
directly affects the lifecycle of the Fragment
Fragment
specific lifecycle callbacks are:
onAttach()
: called when is added to Activity
onCreateView()
: creates the view hierarchy of the Fragment
onActivityCreated()
: called when Activity
's onCreate() method returnedonDestroyView()
: called when view hierarchy of Fragment
is removedonDetach()
: called when Fragment
is disassociated with Activity
FragmentManager
class is used to create a FragmentTransaction
commit()
when ready to make changesArticleFragment newFragment = new ArticleFragment();
FragmentTransaction transaction = getFragmentManager().beginTransaction();
/* Replace whatever is in the fragment_container view with this fragment,
and add the transaction to the back stack so the user can navigate back */
transaction.replace(R.id.fragment_container, newFragment);
transaction.addToBackStack(null);
// Commit the transaction
transaction.commit();
Modern applications prefer the usage of Jetpack Navigation over manual fragment transactions.
Fragment
and when only an Activity
?Fragment
, what is required in the layout? Try to replace a
Fragment
dynamically.Fragment
from another Fragment
, what do
you have to consider concerning the lifecycle?