package com.example.handwriting import android.os.Bundle import androidx.activity.ComponentActivity import androidx.activity.compose.setContent import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Surface import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.ui.Modifier import androidx.compose.ui.tooling.preview.Preview import com.example.handwriting.ui.theme.HandWritingTheme class MainActivity : ComponentActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContent { HandWritingTheme { // A surface container using the 'background' color from the theme Surface( modifier = Modifier.fillMaxSize(), color = MaterialTheme.colorScheme.background ) { Greeting("Android") } } } } } @Composable fun Greeting(name: String, modifier: Modifier = Modifier) { Text( text = "Hello $name!", modifier = modifier ) } @Preview(showBackground = true) @Composable fun GreetingPreview() { HandWritingTheme { Greeting("Android") } }请加 button click 事件 ,启动新activity
时间: 2024-03-03 18:52:39 浏览: 131
好的,可以尝试添加以下代码,它会在界面上添加一个按钮,点击后启动一个新的 Activity:
```
import android.content.Intent
import androidx.activity.compose.rememberLauncherForActivityResult
import androidx.activity.result.contract.ActivityResultContracts
import androidx.compose.foundation.layout.Column
import androidx.compose.material3.Button
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.ui.Modifier
setContent {
val showNewActivity = remember { mutableStateOf(false) }
val launcher = rememberLauncherForActivityResult(ActivityResultContracts.StartActivityForResult()) { }
HandWritingTheme {
Surface(
modifier = Modifier.fillMaxSize(),
color = MaterialTheme.colorScheme.background
) {
Column {
Greeting("Android")
Button(onClick = { showNewActivity.value = true }) {
Text("启动新页面")
}
if (showNewActivity.value) {
launcher.launch(Intent(this@MainActivity, NewActivity::class.java))
}
}
}
}
}
class NewActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_new)
}
}
```
需要注意的是,为了启动新的 Activity,我们需要在 AndroidManifest.xml 中注册该 Activity。同时,还需要在 res/layout 文件夹下创建一个名为 activity_new.xml 的布局文件,用于显示新的 Activity 界面。
阅读全文