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))
    }
}
相关推荐
Whisper_Sy9 小时前
Flutter for OpenHarmony移动数据使用监管助手App实战 - 应用列表实现
android·开发语言·javascript·flutter·php
北海屿鹿10 小时前
【MySQL】内置函数
android·数据库·mysql
臻一11 小时前
rk3576+安卓14 ---上电时序调整
android
踢球的打工仔12 小时前
typescript-接口的基本使用(一)
android·javascript·typescript
2501_9159184113 小时前
如何在iPad上找到并打开文件夹的完整指南
android·ios·小程序·uni-app·iphone·webview·ipad
臻一15 小时前
rk3576+安卓14---uboot
android
2501_9445215915 小时前
Flutter for OpenHarmony 微动漫App实战:主题配置实现
android·开发语言·前端·javascript·flutter·ecmascript
2501_9445215916 小时前
Flutter for OpenHarmony 微动漫App实战:动漫卡片组件实现
android·开发语言·javascript·flutter·ecmascript
知1而N16 小时前
电脑上运行APK文件(Android应用程序包),需要借助特定的软件或功能,因为Windows/macOS/Linux系统无法原生直接运行安卓应用
android·macos·电脑
代码s贝多芬的音符17 小时前
HttpURLConnection post多个参数和一个图片
android·httpurlconn