Saturday, October 2, 2021

jetpack compose - How to use BadgeBox

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.Favorite
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.unit.dp


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


    @ExperimentalMaterialApi
    @Composable
    fun GetScaffold(){
        var favCounter = remember {mutableStateOf(1)}

        Scaffold(
            topBar = { TopAppBarContent(favCounter) },
            content = {MainContent(favCounter)},
            backgroundColor = Color(0xFFEDEAE0)
        )
    }


    @ExperimentalMaterialApi
    @Composable
    fun TopAppBarContent(favCounter: MutableState<Int>) {
        TopAppBar(
            title = { Text(text = "Compose - BadgeBox")},
            backgroundColor = Color(0xFFC0E8D5),
            actions = {
                BadgeBox(
                    badgeContent = {
                        Text("${favCounter.value}")
                    }
                ) {
                    Icon(
                        Icons.Filled.Favorite,
                        contentDescription = "Favorite"
                    )
                }
                Spacer(modifier = Modifier.requiredWidth(12.dp))
            }
        )
    }


    @Composable
    fun MainContent(favCounter: MutableState<Int>){
        Box(
            modifier = Modifier.fillMaxSize(),
            contentAlignment = Alignment.Center
        ){
            Button(
                onClick = {
                    favCounter.value++
                }
            ) {
                Text(text ="Update Badge")
            }
        }
    }


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