Saturday, March 5, 2022

jetpack compose - TabRow indicator color

MainActivity.kt

package com.cfsuman.jetpackcompose

import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.foundation.border
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 Indicator Color")},
                backgroundColor = Color(0xFF89CFF0),
            )},
            content = { MainContent() },
            backgroundColor = Color(0xFFF0FFFF)
        )
    }


    @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(0xFF2E5894),
                contentColor = Color(0xFFBCD4E6),
                indicator = {
                    TabRowDefaults.Indicator(
                        modifier = Modifier
                            .tabIndicatorOffset(it[selectedIndex]),
                        color = Color(0xFFDE5D83),
                        height = TabRowDefaults.IndicatorHeight * 1.5F
                    )
                }
            ) {
                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)
                )
            }
        }
    }
}