Monday, October 4, 2021

jetpack compose - TopAppBar navigation

MainActivity.kt

package com.cfsuman.jetpackcompose

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import androidx.activity.compose.setContent
import androidx.compose.foundation.layout.*
import androidx.compose.material.*
import androidx.compose.runtime.*
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.material.Text
import androidx.compose.material.TopAppBar
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Menu
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.unit.dp
import kotlinx.coroutines.launch


class MainActivity : AppCompatActivity() {
    @ExperimentalMaterialApi
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContent {
            GetScaffold()
        }
    }


    @ExperimentalMaterialApi
    @Composable
    fun GetScaffold(){
        val scaffoldState:ScaffoldState = rememberScaffoldState(
            rememberDrawerState(DrawerValue.Closed)
        )

        Scaffold(
            scaffoldState = scaffoldState,
            topBar = { TopAppBarContent(scaffoldState) },
            content = {MainContent()},
            backgroundColor = Color(0xFFEDEAE0),
            drawerContent = { Text(
                text = "Drawer Content",
                Modifier.padding(12.dp)
            )},
            drawerBackgroundColor = Color(0xFFE3DAC9)
        )
    }


    @ExperimentalMaterialApi
    @Composable
    fun TopAppBarContent(scaffoldState: ScaffoldState) {
        val scope = rememberCoroutineScope()

        TopAppBar(
            title = { Text(text = "Compose - TopAppBar Navigation")},
            backgroundColor = Color(0xFFC0E8D5),
            navigationIcon = {
                IconButton(
                    onClick = { scope.launch {
                        scaffoldState.drawerState.open() }
                    })
                {
                    Icon(
                        Icons.Filled.Menu,
                        contentDescription = "Localized Description"
                    )
                }
            }
        )
    }


    @Composable
    fun MainContent(){
        Box(
            modifier = Modifier.fillMaxSize(),
            contentAlignment = Alignment.Center
        ){
            Text(
                text = "Main Content",
                style = MaterialTheme.typography.h5
            )
        }
    }


    @Preview
    @Composable
    fun ComposablePreview(){
        //GetScaffold()
    }
}