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))
    }
}
相关推荐
炸炸鱼.2 小时前
Python 操作 MySQL 数据库
android·数据库·python·adb
用户41659673693553 小时前
nextlib 项目架构与深度技术指南 (Architecture & Technical Master Guide)
android
aq55356004 小时前
Laravel10.x重磅升级,新特性一览
android·java·开发语言
Trouvaille ~4 小时前
【MySQL篇】数据类型:存储数据的基础
android·数据库·mysql·adb·字符集·数据类型·基础入门
2401_885885045 小时前
开发视频短信接口好开发吗?图文视频短信接口对接教程
android·音视频
千码君20166 小时前
kotlin:Jetpack Compose 给APP添加声音(点击音效/背景音乐)
android·开发语言·kotlin·音效·jetpack compose
Fᴏʀ ʏ꯭ᴏ꯭ᴜ꯭.6 小时前
MySQL半同步复制与GTID实战详解
android·mysql·adb
用户41659673693558 小时前
深度解码:记一次视频时间戳(PTS)异常导致的播放故障排查
android
大白菜和MySQL9 小时前
linux系统环境常用命令
android·linux·adb
Ehtan_Zheng10 小时前
彻底告别 AndroidX 依赖:如何在 KMP 中构建 100% 复用的 UI 逻辑层?
android