Saturday, March 5, 2022

jetpack compose - TabRow custon indicator

MainActivity.kt

package com.cfsuman.jetpackcompose

import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.*
import androidx.compose.material.*
import androidx.compose.material.TabRowDefaults.tabIndicatorOffset
import androidx.compose.runtime.*
import androidx.compose.ui.graphics.Color
import androidx.compose.material.Text
import androidx.compose.material.TopAppBar
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.text.TextStyle
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp


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


    @Composable
    fun GetScaffold() {
        Scaffold(
            topBar = {TopAppBar(
                title = {Text(text = "Compose - TabRow Custom Indicator")},
                backgroundColor = Color(0xFFA9B2C3),
            )},
            content = { MainContent() },
            backgroundColor = Color(0xFFEDEAE0)
        )
    }


    @Composable
    fun MainContent() {
        var selectedIndex by remember { mutableStateOf(0)}
        val tabs = listOf("Tab A","Tab B","Tab C","Tab D")

        Column(Modifier.fillMaxSize()) {
            TabRow(
                selectedTabIndex = selectedIndex,
                backgroundColor = Color(0xFF7BB661),
                contentColor = Color(0xFFFEFEFA),
                indicator = {
                    Spacer(
                        Modifier
                            .tabIndicatorOffset(it[selectedIndex])
                            .height(2.5.dp)
                            .background(Color(0xFFE30022))
                    )
                }
            ) {
                tabs.forEachIndexed { index, tab ->
                    Tab(
                        selected = selectedIndex == index,
                        onClick = { selectedIndex = index},
                    ) {
                        Text(
                            text = tab,
                            modifier = Modifier.padding(12.dp)
                        )
                    }
                }
            }

            Box(Modifier.fillMaxSize().wrapContentSize(Alignment.Center)) {
                Text(
                    text = tabs[selectedIndex],
                    style = TextStyle(fontSize = 30.sp)
                )
            }
        }
    }
}