https://kotlinlang.org logo
#compose
Title
# compose
t

Ttop

09/10/2020, 2:39 PM
Hi, I’m learning to use Compose and I’m trying to use Tab in a layout like this
Copy code
class TabContent(val header: String, val icon: Int, val content: @Composable () -> Unit)

@Composable
fun BodyContent() {
    var index = 0
    val updateTab : (currentIndex: Int) -> Unit = { index = it }

    val tabs = listOf(
        TabContent(
            header = stringResource(id = R.string.depenses_tab_title).toUpperCase(
                Locale.getDefault()
            ),
            icon = R.drawable.ic_depenses
        ) { DepenseTabContent(Modifier) },
        TabContent(
            header = stringResource(id = R.string.equilibre_tab_title).toUpperCase(
                Locale.getDefault()
            ),
            icon = R.drawable.ic_equilibres
        ) { Text ( text= "blop") }
    )

    BodyContent(index, updateTab, tabs)
}

@Composable
fun BodyContent(
    selectedTabIndex: Int,
    updateTab: (Int) -> Unit,
    tabs: List<TabContent>,
    modifier: Modifier = Modifier
) {
    Column(modifier.fillMaxSize()) {
        TabRow(selectedTabIndex = selectedTabIndex) {
            tabs.forEachIndexed { index, tabContent ->
                Tab(
                    selected = selectedTabIndex == index,
                    onClick = { updateTab(index) },
                    text = { Text(text = tabContent.header) },
                    icon = {
                        Icon(
                            vectorResource(id = tabContent.icon),
                            Modifier.width(24.dp).height(24.dp)
                        )
                    }
                )
            }
        }
        Box {
            tabs[selectedTabIndex].content
        }
    }
}
My tab content is never displayed and I can’t refresh it by clicking in the tabRow. I don’t understand what I’v done wrong.
👍 1
t

Timo Drick

09/10/2020, 3:03 PM
I think you should change the decleration of you index to:
var index = remember { mutableStateOf(0) }
👍 2
Not sure maybe it works alsp with
var index by remember { mutableStateOf(0) }
t

Ttop

09/10/2020, 3:11 PM
it seems it doesn’t change anything
t

Timo Drick

09/10/2020, 4:21 PM
Can you please try to just show a Text() with the index instead of your content. Does this work?
t

Ttop

09/10/2020, 4:32 PM
yes it does display 0
t

Timo Drick

09/10/2020, 4:44 PM
Ah you just forget the ()
tabs[selectedTabIndex].content()
🤗 1
t

Ttop

09/10/2020, 4:48 PM
that’s it! thx. but when I click on the unselected tab, the screen is not refreshed
t

Timo Drick

09/10/2020, 5:10 PM
That should be because of your index decleration. it should be
var index by remember { mutableStateOf(0) }
m

Mahdi

10/17/2020, 12:29 AM
@Ttop Hi. I'm using your code for tabs but some how dynamic contents are not drawing. and their compose function do not trigger at all;
Copy code
tabs[selectedTabIndex].content
Do you have this issue?