Navigate from IconButton in an item in Lazycolumn - android

I want to navigate to another screen after clicking on the IconButton in TaskItem.kt but it doesn't work. Logcat doesn't show anything, there aren't any errors in "Run". After clicking the edit IconButton it should navigate to another screen.
Screen.kt:
package com.example.planner
sealed class Screen(val route: String) {
object TasksList: Screen(route = "tasks_list")
object AddScreen: Screen(route = "add_screen")
object UpdateScreen: Screen(route = "update_screen")
}
NavGraph.kt:
package com.example.planner
import androidx.compose.runtime.Composable
import androidx.navigation.NavHostController
import androidx.navigation.compose.NavHost
import androidx.navigation.compose.composable
#Composable
fun Navigation(navController: NavHostController) {
NavHost(navController = navController, startDestination = Screen.TasksList.route)
{
composable(
route = Screen.TasksList.route
) {
TasksList(navController = navController)
}
composable(
route = Screen.AddScreen.route
) {
AddScreen(navController = navController)
}
composable(
route = Screen.UpdateScreen.route
) {
UpdateScreen(navController = navController)
}
}
}
Part of TaskItem.kt:
IconButton(onClick = { navController.navigate(route = Screen.UpdateScreen.route) }, modifier = Modifier.size(36.dp)) {
Icon(
imageVector = Icons.Filled.Edit,
contentDescription = "Edit",
modifier = Modifier.padding(horizontal = 2.dp),
tint = MaterialTheme.colorScheme.onBackground
)
}
MainActivity.kt:
class MainActivity : ComponentActivity() {
private lateinit var navController: NavHostController
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContent {
PlannerTheme {
// A surface container using the "background" color from the theme
Surface(
modifier = Modifier.fillMaxSize(),
color = MaterialTheme.colorScheme.background
) {
navController = rememberNavController()
Navigation(navController = navController)
MyApp(Modifier.fillMaxSize(), navController)
}
}
}
}
}
#Composable
fun MyApp(modifier: Modifier = Modifier, navController: NavController) {
Surface(modifier, color = MaterialTheme.colorScheme.background) {
TasksList(navController = navController)
}
}
#Preview(name = "LightMode", showBackground = true)
#Preview(name = "DarkMode", showBackground = true, uiMode = Configuration.UI_MODE_NIGHT_YES)
#Preview(name = "FullPreview", showBackground = true, showSystemUi = true)
#Composable
fun DefaultPreview() {
PlannerTheme {
Surface(modifier = Modifier, color = MaterialTheme.colorScheme.background) {
TasksList(navController = rememberNavController())
}
}
}

MyApp(Modifier.fillMaxSize(), navController),Is this sentence redundant? Just remove it.

Related

Home and Auth navigation flows in Jetpack Compose

I have a problem with navigation in my Compose app. So starting from the beginning I want to have two navigation graphs: one for authentication related things and second for main functionalities, which should be accessible only after login. So typical case.
I want to use Splash Screen API from Android 12, so in my main activity I could do something like this:
class AppMainActivity : ComponentActivity() {
private val viewModel by viewModels<SplashViewModel>()
private var userAuthState: UserAuthState = UserAuthState.UNKNOWN
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
viewModel.onEvent(SplashEvent.CheckAuthentication)
lifecycleScope.launch {
repeatOnLifecycle(Lifecycle.State.STARTED) {
viewModel.isAuthenticated.collect {
userAuthState = it
}
}
}
setContent {
CarsLocalizerTheme {
Surface(
modifier = Modifier.fillMaxSize(),
color = MaterialTheme.colors.background
) {
val scaffoldState = rememberScaffoldState()
val navController = rememberNavController()
Scaffold(
modifier = Modifier.fillMaxSize(),
scaffoldState = scaffoldState
) {
val splash = installSplashScreen()
splash.setKeepOnScreenCondition {
userAuthState != UserAuthState.UNKNOWN
}
when (userAuthState) {
UserAuthState.UNAUTHENTICATED -> {
AuthNavigation(
navController = navController,
scaffoldState = scaffoldState
)
}
UserAuthState.AUTHENTICATED -> {
HomeScreen(
viewModel = hiltViewModel(),
onLogout = { navController.popBackStack() }
)
}
UserAuthState.UNKNOWN -> {}
}
}
}
}
}
}
}
Here I am collecting StateFlow from view model, which describes if user is authenticated already or no. If authenticated successfully then go to HomeScreen, which has HomeNavigation inside. If not authenticated, go to Authentication nav graph. Problem is that this approach would not work, since activity is created only once, so if I user will login, this when
when (userAuthState) {
UserAuthState.UNAUTHENTICATED -> {
AuthNavigation(
navController = navController,
scaffoldState = scaffoldState
)
}
UserAuthState.AUTHENTICATED -> {
HomeScreen(
viewModel = hiltViewModel(),
onLogout = { navController.popBackStack() }
)
}
UserAuthState.UNKNOWN -> {}
}
Won’t be called again.
I was trying to find some solution for my problem but, can’t find anything helpful. Maybe somebody had such issue before, or saw something useful? Will be very glad for any help.
Rest of my code:
SplashViewModel
#HiltViewModel
class SplashViewModel #Inject constructor(
private val authenticateUseCase: AuthenticateUseCase
): ViewModel() {
private val _isAuthenticated = MutableStateFlow<UserAuthState>(value = UserAuthState.UNKNOWN)
val isAuthenticated: StateFlow<UserAuthState> = _isAuthenticated.asStateFlow()
fun onEvent(event: SplashEvent) {
when (event) {
is SplashEvent.CheckAuthentication -> {
viewModelScope.launch {
val result = authenticateUseCase()
when (result) {
true -> {
_isAuthenticated.emit(UserAuthState.AUTHENTICATED)
}
false -> {
_isAuthenticated.emit(UserAuthState.UNAUTHENTICATED)
}
}
}
}
}
}
}
AuthNavigation
#Composable
fun AuthNavigation(
navController: NavHostController,
scaffoldState: ScaffoldState
) {
NavHost(
navController = navController,
startDestination = Screen.Login.route,
modifier = Modifier.fillMaxSize()
) {
composable(Screen.Login.route) {
LoginScreen(
onNavigate = { navController.navigate(it) } ,
onLogin = {
navController.popBackStack()
},
scaffoldState = scaffoldState,
viewModel = hiltViewModel()
)
}
composable(Screen.Register.route) {
RegisterScreen(
onPopBackstack = { navController.popBackStack() },
scaffoldState = scaffoldState,
viewModel = hiltViewModel()
)
}
composable(Screen.Onboarding.route) {
OnboardingScreen(
onCompleted = { navController.popBackStack() },
viewModel = hiltViewModel()
)
}
}
}
HomeScreen
#Composable
fun HomeScreen(
viewModel: HomeViewModel,
onLogout: () -> Unit
) {
val navController = rememberNavController()
val scaffoldState = rememberScaffoldState()
var appBarTitle by remember {
mutableStateOf("")
}
LaunchedEffect(key1 = true) {
viewModel.userName.collectLatest {
appBarTitle = "Hello $it"
}
}
Scaffold(
scaffoldState = scaffoldState,
topBar = {
if (appBarTitle.isEmpty()) {
AppBarWithName("Hello")
} else {
AppBarWithName(appBarTitle)
}
},
bottomBar = { BottomNavigationBar(navController) },
content = { padding ->
Box(modifier = Modifier.padding(padding)) {
HomeNavigation(
navController = navController,
scaffoldState = scaffoldState,
onLogout = { onLogout() }
)
}
}
)
}
HomeNavigation
#Composable
fun HomeNavigation(
navController: NavHostController,
scaffoldState: ScaffoldState,
onLogout: () -> Unit
) {
NavHost(
navController = navController,
startDestination = Screen.Map.route
) {
composable(Screen.Map.route) {
MapScreen(viewModel = hiltViewModel())
}
composable(Screen.ManageCars.route) {
ManageCarsScreen(
viewModel = hiltViewModel(),
scaffoldState = scaffoldState,
onAddCar = {
navController.navigate(Screen.AddCar.route)
}
)
}
composable(Screen.AddCar.route) {
AddCarScreen(
viewModel = hiltViewModel(),
onPopBackstack = {
navController.popBackStack()
}
)
}
composable(Screen.Logout.route) {
LogoutDialogScreen(
viewModel = hiltViewModel(),
onLogout = {
navController.popBackStack()
onLogout()
},
onCancel = {
navController.popBackStack()
}
)
}
}
}
You need to store the UserAuthState as MutableState, this way, when the value is updated, setContent will automatically re-compose:
private var userAuthState = mutableStateOf(UserAuthState.UNKNOWN)
lifecycleScope.launch {
repeatOnLifecycle(Lifecycle.State.STARTED) {
viewModel.isAuthenticated.collect { userAuthState.value = it }
}
}
setContent {
when (userAuthState.value) {
etc....
}
}
From the docs:
mutableStateOf creates an observable MutableState, which is an
observable type integrated with the compose runtime.
Any changes to value schedules recomposition of any composable
functions that read value.

Jetpack Compose How to pass arguments between screens with Hilt ViewModel using savedStateHandle?

Recently in my app I've been using simple navigation component arguments passing. Since I've added Hilt ViewModel, i came across something called saveStateHandle and apparently I can pass arguments between screens easly with this. How can i do that? I implemented the code in my HiltViewModel
#HiltViewModel
class ExerciseViewModel #Inject constructor(
private val repository: ExerciseRepository,
savedStateHandle: SavedStateHandle
) : ViewModel() {
val data: MutableState<DataOrException<List<Exercise>, Boolean, Exception>> =
mutableStateOf(
DataOrException(null, true, Exception(""))
)
val muscleGroup: String? = savedStateHandle[Constants.MUSCLE_GROUP_KEY]
private val _exerciseListFromDb = MutableStateFlow<List<Exercise>>(emptyList())
val exerciseListFromDb = _exerciseListFromDb.asStateFlow()
init {
getExercises()
viewModelScope.launch(Dispatchers.IO) {
repository.getAllExercisesFromDb().collect() {
_exerciseListFromDb.value = it
}
}
}
private fun getExercises() {
viewModelScope.launch {
data.value.loading = true
data.value = repository.getExercises()
if (data.value.data.toString().isNotEmpty())
data.value.loading = false
}
}
fun insertExerciseToDb(exercise: Exercise) = viewModelScope.launch {
repository.insertExerciseToDb(exercise)
}
fun deleteExerciseFromDb(exercise: Exercise) = viewModelScope.launch {
repository.deleteExerciseFromDb(exercise)
}
}
I want to pass muscleGroup parameter between screens HomeScreen -> SampleExercisesScreen. How do I send parameter from HomeScreen to HiltViewModel ExerciseViewModel and then use it in SampleExercisesScreen and other screens?
#Composable
fun HomeScreen(navController: NavController) {
Surface(modifier = Modifier.fillMaxSize(),
color = AppColors.mBackground) {
Column {
Header()
Row(modifier = Modifier
.fillMaxWidth()
.padding(top = 50.dp)){
MuscleButton(modifier = Modifier.weight(1f), icon = R.drawable.body, muscleGroup = "Chest", navController)
MuscleButton(modifier = Modifier.weight(1f), icon = R.drawable.male, muscleGroup = "Back", navController)
MuscleButton(modifier = Modifier.weight(1f), icon = R.drawable.shoulder, muscleGroup = "Shoulders", navController)
}
Row(modifier = Modifier.fillMaxWidth()){
MuscleButton(modifier = Modifier.weight(1f), icon = R.drawable.muscle, muscleGroup = "Biceps", navController)
MuscleButton(modifier = Modifier.weight(1f), icon = R.drawable.triceps, muscleGroup = "Triceps", navController)
MuscleButton(modifier = Modifier.weight(1f), icon = R.drawable.leg, muscleGroup = "Legs", navController)
}
}
}
},
#Composable
fun SampleExerciseScreen(navController: NavController, muscleGroup: String, exerciseList: List<Exercise>?) {
val mExerciseList = exerciseList!!.filter { it.muscle == muscleGroup }
Log.d("TEST", "$mExerciseList, $muscleGroup")
Surface(modifier = Modifier.fillMaxSize(),
color = AppColors.mBackground) {
Column {
MyTopBar(navController = navController)
LazyColumn(Modifier.weight(1f)){
items(mExerciseList) {
ExerciseRow(exercise = it)
}
}
GoToButton(navController = navController, text = "YOUR EXERCISES", route = Screen.UserExercises.passMuscleGroup(muscleGroup))
}
}
}
NavGraph
#Composable
fun SetupNavGraph(navController: NavHostController, viewModel: ExerciseViewModel) {
val exerciseList = viewModel.data.value.data?.toList()
val exerciseListFromDb = viewModel.exerciseListFromDb.collectAsState().value
val muscleGroup = viewModel.muscleGroup
NavHost(navController = navController, startDestination = Screen.Home.route) {
composable(
route = Screen.Home.route
) {
HomeScreen(navController = navController)
}
composable(
route = Screen.SampleExercise.route,
) {
SampleExerciseScreen(
navController = navController,
muscleGroup = muscleGroup.toString(),
exerciseList = exerciseList
)
}
composable(
route = Screen.UserExercises.route,
arguments = listOf(navArgument(MUSCLE_GROUP_KEY) {
type = NavType.StringType
})
) {
UserExercisesScreen(
navController = navController,
muscleGroup = it.arguments?.getString(MUSCLE_GROUP_KEY).toString(),
viewModel = viewModel,
exerciseListFromDb = exerciseListFromDb
)
}
composable(
route = Screen.Add.route,
arguments = listOf(navArgument(MUSCLE_GROUP_KEY) {
type = NavType.StringType
})
) {
AddScreen(
navController = navController, muscleGroup = it.arguments?.getString(MUSCLE_GROUP_KEY).toString(),
viewModel = viewModel
)
}
}
}
I have a blog post here that explains it: https://www.francescvilarino.com/passing-arguments-to-screens-in-jetpack-compose
But basically you have to retrieve the arguments in the viewmodel from the SavedStateHandle, using the key that you used in your route for each argument.
navController.navigate(buildTwoRoute(argument))
then
#HiltViewModel
class TwoViewModel #Inject constructor(
savedStateHandle: SavedStateHandle,
) : ViewModel() {
init {
val argument = savedStateHandle.get<String>(DestinationOneArg).orEmpty()
}
}

Jetpack Compose Accompanist Navigation: Blank screen after splash screen

I have a splash screen that I show when the app launch. I'm using SplashScreenAPI for the splash screen. I'm also using accompanist navigation library to navigate with animations. After I updated the accompanist version from 0.24.7-alpha to 0.24.8-beta I've encountered an issue. The issue is :
As you can see after the splash screen is shown there is a blank screen for a sec, then it navigates to the start destination.
Here is also the behavior for version 0.24.7-alpha:
In case of need here is also the code:
#OptIn(ExperimentalMaterial3WindowSizeClassApi::class)
#AndroidEntryPoint
class AuthActivity : ComponentActivity() {
private val splashViewModel: SplashViewModel by viewModels()
private lateinit var splashScreen: SplashScreen
override fun onCreate(savedInstanceState: Bundle?) {
splashScreen = installSplashScreen()
super.onCreate(savedInstanceState)
splashScreen.setKeepOnScreenCondition {
splashViewModel.isLoading.value
}
splashScreen.setOnExitAnimationListener {
val startDestination = splashViewModel.navDestination.value.route
if (startDestination == AUTH_GRAPH) {
it.remove()
} else {
val intent = Intent(this#AuthActivity, MainActivity::class.java)
startActivity(intent)
finish()
}
}
setContent {
val errorMessage by splashViewModel.errorFlow.collectAsState()
val widthSizeClass = calculateWindowSizeClass(this).widthSizeClass
ProvideLocalWindowWidthSizeClass(widthSizeClass = widthSizeClass) {
RubiBrandsTheme {
RubiBrandsBackground {
errorMessage?.asString(this#AuthActivity)?.let {
ErrorDialog(message = it)
}
AuthNavGraph(
navController = rememberAnimatedNavController(),
activity = this#AuthActivity
)
}
}
}
}
}
}
I just check the authentication and then navigate the user based on success or not.
Here is my MainActivity :
#[AndroidEntryPoint OptIn(ExperimentalMaterial3WindowSizeClassApi::class)]
class MainActivity : ComponentActivity(), AuthenticationManager {
private val mViewModel by viewModels<MainActivityViewModel>()
#Inject
lateinit var authenticationMediator: AuthenticationMediator
private lateinit var navController: NavHostController
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
WindowCompat.setDecorFitsSystemWindows(window, false)
authenticationMediator.registerAuthenticationManager(this)
setContent {
val widthSizeClass = calculateWindowSizeClass(this).widthSizeClass
val showUnauthorizedDialog = mViewModel.showUnauthorizedDialog
ProvideLocalWindowWidthSizeClass(widthSizeClass = widthSizeClass) {
RubiBrandsTheme {
RubiBrandsBackground {
navController = rememberAnimatedNavController()
val bottomSheetNavigator =
rememberBottomSheetNavigator()
val scaffoldState = rememberScaffoldState()
navController.navigatorProvider += bottomSheetNavigator
val navBackStackEntry by navController.currentBackStackEntryAsState()
val currentDestination = navBackStackEntry?.destination
val rubiBrandsTopLevelNavigation = remember(navController) {
RubiBrandsTopLevelNavigation(navController)
}
val topLevelDestinations = listOf(
TopLevelDestination.DashboardDestination,
TopLevelDestination.OrdersDestination,
TopLevelDestination.ProductsDestination,
TopLevelDestination.AccountDestination
)
val topLevelDestinationRoutes =
topLevelDestinations.map(TopLevelDestination::route)
val isNavBarVisible =
navBackStackEntry?.destination?.route in topLevelDestinationRoutes
ModalBottomSheetLayout(
modifier = Modifier
.systemBarsPadding()
.imePadding(),
bottomSheetNavigator = bottomSheetNavigator,
sheetElevation = dimensionResource(id = R.dimen.dimen_16),
sheetShape = RoundedCornerShape(
topStart = dimensionResource(id = R.dimen.dimen_16),
topEnd = dimensionResource(
id = R.dimen.dimen_16
)
),
sheetBackgroundColor = RubiBrandsTheme.colors.filterBottomSheetBackgroundColor
) {
RubiBrandsScaffold(
modifier = Modifier
.systemBarsPadding()
.imePadding(),
bottomBar = {
if (isNavBarVisible) {
RubiBrandsBottomNavigationView(
onNavigateToTopLevelDestination = rubiBrandsTopLevelNavigation::navigateTo,
currentDestination = currentDestination,
topLevelDestinations = topLevelDestinations
)
}
},
scaffoldState = scaffoldState
) {
//navigation graph
Box(
modifier = Modifier
.padding(it)
) {
MainNavGraph(
navController = navController,
mainActivity = this#MainActivity,
mainActivityViewModel = mViewModel,
)
showUnauthorizedDialog?.getContentIfNotHandled()?.let { show ->
if (show) {
RubiBrandsUnauthorizedScreen {
logClickEvent(ItemNames.UNAUTHORIZED_DIALOG_OKAY_BUTTON)
logout()
}
}
}
}
}
}
}
}
}
}
}
#Composable
fun MainNavGraph(
navController: NavHostController,
modifier: Modifier = Modifier,
) {
AnimatedNavHost(
navController = navController,
startDestination = MAIN_GRAPH,
) {
//main nav graph
mainNavGraph(navController)
}
fun NavGraphBuilder.mainNavGraph(
navController: NavController
) {
navigation(
startDestination = TopLevelDestination.DashboardDestination.route,
route = MAIN_GRAPH,
) {
addDashboardScreen(navController)
}
}
Here is also compose dependencies and the versions :
object Compose : Library {
object Version {
const val COMPOSE_VERSION = "1.2.0"
const val COMPOSE_ACTIVITY_VERSION = "1.5.1"
const val COMPOSE_CONSTRAINT_LAYOUT_VERSION = "1.0.1"
const val HILT_NAVIGATION_COMPOSE_VERSION = "1.0.0"
}
const val COMPOSE_UI = "androidx.compose.ui:ui:$COMPOSE_VERSION"
const val COMPOSE_MATERIAL = "androidx.compose.material:material:$COMPOSE_VERSION"
const val COMPOSE_UI_TOOLING_PREV =
"androidx.compose.ui:ui-tooling-preview:$COMPOSE_VERSION"
const val COMPOSE_ACTIVITY = "androidx.activity:activity-compose:$COMPOSE_ACTIVITY_VERSION"
const val COMPOSE_UI_TOOLING = "androidx.compose.ui:ui-tooling:$COMPOSE_VERSION"
const val COMPOSE_UI_TEST_MANIFEST = "androidx.compose.ui:ui-test-manifest:$COMPOSE_VERSION"
const val COMPOSE_CONSTRAINT_LAYOUT =
"androidx.constraintlayout:constraintlayout-compose:$COMPOSE_CONSTRAINT_LAYOUT_VERSION"
const val HILT_NAVIGATION_COMPOSE =
"androidx.hilt:hilt-navigation-compose:$HILT_NAVIGATION_COMPOSE_VERSION"
const val COMPOSE_LIVE_DATA = "androidx.compose.runtime:runtime-livedata:$COMPOSE_VERSION"
override val components: List<String>
get() = listOf(
COMPOSE_UI,
COMPOSE_MATERIAL,
COMPOSE_UI_TOOLING_PREV,
COMPOSE_ACTIVITY,
)
}
I know that my compose version should be compatible with the accompanist version. As per this I should set the accompanist version to 0.25.1 but because of this issue, I don't update the animation version.

why it throw an error for NavController as a NullPointerException in jetpack compose?

I try to learning jetpack compose in android, so I want to use navController in a simple project, when I debug the project it throw an error as a
NullPointerException when trying to get NavController
for in this onClick = {navController.navigate("screenB")} line of code. I do not know what I missed in this project?. I was search on internet to solve it, but I am still not get it.
#AndroidEntryPoint
class NavActivity : ComponentActivity() {
private lateinit var viewModel: MyViewModel
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
viewModel = ViewModelProvider(this)[MyViewModel::class.java]
setContent {
NavScreen()
}
}
}
#Composable
fun NavScreen() {
val viewModel = hiltViewModel<MyViewModel>()
val navController = rememberNavController()
NavHost(navController = navController, startDestination = "screenA") {
composable(route = "screenA") {
ScreenA(navController)
}
composable(route = "screenB") {
ScreenB(navController)
}
}
}
ScreenA:
#AndroidEntryPoint
class ScreenA : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContent {
val navController = rememberNavController()
ScreenA(navController)
}
}
}
#Composable
fun ScreenA(
navController: NavController
) {
Button(
modifier = Modifier
.width(30.dp)
.height(15.dp),
onClick = {
navController.navigate("screenB")
},
colors = ButtonDefaults.buttonColors(
backgroundColor = Color.Red
),
shape = RoundedCornerShape(20)
) {
Text(
text = "OK",
)
}}
ScreenB:
#OptIn(ExperimentalComposeUiApi::class)
#Composable
fun ScreenB(
navController: NavController
) {
}
ScreenA should be composable not Activity. Try to leave only composable component in ScreenA
#Composable
fun ScreenA(
navController: NavController
) {
Button(
modifier = Modifier
.width(30.dp)
.height(15.dp),
onClick = {
navController.navigate("screenB")
},
colors = ButtonDefaults.buttonColors(
backgroundColor = Color.Red
),
shape = RoundedCornerShape(20)
) {
Text(
text = "OK",
)
}}

How navigate with drawer in jetpack compose?

I am developing an application in which I have added a side navigation menu. I have also added the menu icon in the TopBar. When this button is pressed, the side menu is displayed with its options (Data and About).
I don't know how to achieve the following:
When I am in the Data window I want the TopBar icon to be the menu or hamburger icon
When in the About window I want the TopBar icon to be the back arrow
When you are in the About window and click on the back arrow of step 2, I want you to return to the Data window
With the attached code, I can navigate between the Data and About window, but I have no way to go back, except with Android's own button in the bottom bar. My intention is to be able to navigate with the TopBar button
MainActivity
#AndroidEntryPoint
class MainActivity : ComponentActivity() {
private val viewModel: MyViewModel by viewModels()
#ExperimentalMaterialApi
#ExperimentalAnimationApi
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
WindowInsetsControllerCompat(window, window.decorView).isAppearanceLightNavigationBars = true
setContent {
MyTheme {
Surface(color = MaterialTheme.colors.background) {
MainScreen(viewModel = viewModel)
}
}
}
}
}
#ExperimentalAnimationApi
#ExperimentalMaterialApi
#Composable
fun MainScreen(
viewModel: MyViewModel
) {
val navController = rememberNavController()
val scaffoldState = rememberScaffoldState(
drawerState = rememberDrawerState(initialValue = DrawerValue.Closed)
)
val scope = rememberCoroutineScope()
val navigationItems = listOf(
Screen.DataScreen,
Screen.SettingsScreen
)
Scaffold(
scaffoldState = scaffoldState,
topBar = { TopBar(navController = navController, scope = scope, scaffoldState = scaffoldState) },
drawerContent = { Drawer(scope = scope, scaffoldState = scaffoldState, navController = navController, items = navigationItems) },
drawerGesturesEnabled = true
) {
NavigationHost(navController, viewModel, params)
}
}
TopBar:
#Composable
fun TopBar(
navController: NavHostController,
scope: CoroutineScope,
scaffoldState: ScaffoldState
) {
TopAppBar(
title = {
Text(
stringResource(R.string.app_name),
fontWeight = FontWeight.Bold
)
},
navigationIcon =
{
IconButton(onClick = {
scope.launch {
scaffoldState.drawerState.open()
}
}) {
Icon(imageVector = Icons.Filled.Menu, contentDescription = "Menu Icon")
}
}
)
}
Drawer:
#Composable
fun Drawer(
scope: CoroutineScope,
scaffoldState: ScaffoldState,
navController: NavHostController,
items: List<Screen>
) {
val currentRoute = currentRoute(navController)
Column(modifier = Modifier.fillMaxWidth()) {
Row(
modifier = Modifier
.fillMaxWidth()
) {
Column {
Text(
text = stringResource(id = R.string.app_name),
color = Color.White
)
Text(
text = stringResource(id = R.string.app_description),
color = Color.Black
)
}
}
Row(
modifier = Modifier
.fillMaxWidth()
) {
Column {
items.forEach { item ->
DrawerItem(item = item, selected = currentRoute == item.route) {
navController.navigate(item.route) {
launchSingleTop = true
}
scope.launch {
scaffoldState.drawerState.close()
}
}
}
}
}
}
}
#Composable
fun DrawerItem(
item: Screen,
selected: Boolean,
onItemClick: (Screen) -> Unit
) {
Row(
modifier = Modifier
.fillMaxWidth()
.clickable { onItemClick(item) }
) {
Icon(
modifier = Modifier.size(32.dp),
imageVector = item.icon,
contentDescription = item.title
)
Spacer(modifier = Modifier.width(12.dp))
Text(
text = item.title
)
}
}
NavigationHost:
#Composable
fun NavigationHost(
navController: NavHostController,
viewModel: MyViewModel
) {
NavHost(navController = navController, startDestination = Screen.DataScreen.route) {
composable(Screen.DataScreen.route) {
DataScreen(
navController = navController,
viewModel = viewModel
)
}
composable(Screen.SettingsScreen.route) {
SettingsScreen(
navController = navController
)
}
}
}
Screen:
sealed class Screen(
val route: String,
val title: String,
val icon: ImageVector
) {
object DataScreen :
Screen("data_screen", "Data", Icons.Filled.LocationOn)
object SettingsScreen :
Screen("settings_screen", "About", Icons.Filled.Info)
}

Categories

Resources