android compose Tab(顶部) 使用

android compose Tab(顶部) 使用

复制代码
/**
 * Author : wn
 * Email : maoning20080809@163.com
 * Date : 2026/1/3 12:44
 * Description : 使用 TabRow 和 Tab 实现切换 (顶部)
 */
class TabActivity : ComponentActivity(){

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        setContent {
            testTab()
        }
    }

    @Preview
    @Composable
    private fun testTab(){
        //要添加Composable,导入:import androidx.compose.runtime.getValue 和 import androidx.compose.runtime.setValue
        var selectedTabIndex by remember { mutableStateOf(0) }
        val tabs = listOf("Tab 1", "Tab 2", "Tab 3")
        Column(modifier = Modifier.fillMaxSize()) {
            TabRow(
                selectedTabIndex = selectedTabIndex,
                containerColor = MaterialTheme.colorScheme.primaryContainer,
                contentColor = MaterialTheme.colorScheme.primaryContainer,
            ) {
                tabs.forEachIndexed {index, title ->
                    Tab(
                        selected = selectedTabIndex == index,
                        onClick = {selectedTabIndex = index},
                        text = {Text(text = title)},
                        selectedContentColor = MaterialTheme.colorScheme.primary,
                        unselectedContentColor = MaterialTheme.colorScheme.onSurfaceVariant
                    )
                }
            }
            when(selectedTabIndex) {
                0 -> tabContent1()
                1 -> tabContent2()
                2 -> tabContent3()
            }
        }
    }

    @Composable
    private fun tabContent1(){
        Text(text = "Tab 1 Content", modifier = Modifier.padding(16.dp))
    }

    @Composable
    private fun tabContent2(){
        Text(text = "Tab 2 Content", modifier = Modifier.padding(16.dp))
    }

    @Composable
    private fun tabContent3(){
        Text(text = "Tab 3 Content", modifier = Modifier.padding(16.dp))
    }
}
相关推荐
冬奇Lab3 小时前
稳定性性能系列之八——系统性能分析基础:Systrace与Perfetto入门
android·性能优化
程序员码歌3 小时前
短思考第268天,自媒体路上的4大坑点,很多人都踩过
android·前端·ai编程
消失的旧时光-19434 小时前
从 Android 组件化到 Flutter 组件化
android·flutter·架构
Android轮子哥5 小时前
Android 12 SplashScreen 一种另类的适配方案
android·github
粤M温同学5 小时前
Android OkHttp 下载限速方案实现
android·okhttp
2501_915106326 小时前
Perfdog 成本变高之后,Windows 上还能怎么做 iOS APP 性能测试
android·ios·小程序·https·uni-app·iphone·webview
愤怒的代码7 小时前
从开发调试到生产上线:全维度 Android 内存监控与分析体系构建
android·java·kotlin
jzlhll1237 小时前
Android最简化发布模块到mavenCentral
android·mavencentral
2501_915106327 小时前
iOS 安装了证书,HTTPS 还是抓不到
android·网络协议·ios·小程序·https·uni-app·iphone
好奇龙猫7 小时前
【人工智能学习-AI-MIT公开课13.- 学习:遗传算法】
android·人工智能·学习