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))
    }
}
相关推荐
事圆则缓1 小时前
Android 开启线程的几种方式:Thread、线程池、HandlerThread 与协程
android
ZealSinger4 小时前
Kotlin后端别再用GlobalScope
kotlin·协程·后端开发·结构化并发
半摆烂日常15 小时前
低代码平台API对接实践:接口鉴权与数据同步的完整实现
android·低代码·rxjava
事圆则缓16 小时前
volatile 使用场景全解析:它能保证什么,又解决不了什么
android
蒲公英内测分发17 小时前
智能投影仪参加海外展会,未上架的 Android 配套 App 怎么让客户限时试用?
android
ii_best17 小时前
按键精灵手机端开发安卓版实战:手写一个可最小化、可拖动的「运行日志悬浮窗」(附完整 源码 + 踩坑记录)
android·ios·智能手机·自动化·ai编程·按键精灵
终端安全笔记17 小时前
安卓做 MDM 管控,先分清三种注册入口
android·安全·智能手机
乌萨达18 小时前
手机模拟器安卓怎么用?电脑安装应用、玩手游与账号同步指南
android·智能手机·电脑·雷电模拟器
美狐美颜SDK开放平台18 小时前
Android与iOS直播APP美颜有什么区别?视频美颜SDK开发详解
android·ios·音视频·视频美颜sdk
春猿火20 小时前
某市-2026【网安·论道】misc-afterimage_note-wp
android