<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
class ExampleDetailFragment : Fragment() {
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View {
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 hierarchyFragments 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 changesval newFragment = ArticleFragment()
val transaction = supportFragmentManager.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()
NavHost
to build the navigation graphPlease see the following example:
@Composable
fun MovieTracker() {
//navController holds the navigation graph
val navController: NavHostController = rememberNavController()
MovieTrackerNavHost(navController = navController)
}
@Composable
fun MovieTrackerNavHost(navController: NavHostController) {
//NavHost builds the navigation graph
NavHost(navController = navController, startDestination = homeScreen) {
composable(homeScreen) {
HomeScreen(
onSearchClick = {
navController.navigate(searchScreen)
}
)
}
composable(searchScreen) {
SearchScreen(
onMovieClick = { currentMovie: Movie ->
navController.popBackStack()
}
)
}
}
}
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?