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))
    }
}
相关推荐
神龙天舞20016 分钟前
MySQL 备库为什么会延迟好几个小时
android·数据库·mysql
码农coding3 小时前
android12 systemUI 之锁屏
android
圆山猫4 小时前
[Virtualization](三):RISC-V H-extension 与 Guest 执行模式
android·java·risc-v
爱笑鱼4 小时前
Binder(七):getCallingUid() 读到的是谁?clearCallingIdentity() 又清掉了什么?
android
2501_9159090610 小时前
iOS 应用反调试技详解术 检测调试器的原理与防护实践
android·ios·小程序·https·uni-app·iphone·webview
Lvan的前端笔记10 小时前
AndroidX 完全入门指南
android·androidx
帅次10 小时前
Android 应用高级面试:Window 近1年高频追问 18 题
android·面试·职场和发展
总捣什么乱111 小时前
MySQL MySQL是怎么保证主备一致的?
android·mysql·adb
zzm62811 小时前
精读 HinDroid:基于异构信息网络的安卓恶意软件检测
android
weixin_4407841112 小时前
Android基础知识汇总
android·java·android studio