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-02-14 22:08:08 浏览: 171
好的,我可以帮您在这段代码中添加button click事件,启动新的activity。请参考下面的代码:
```
package com.example.handwriting
import android.content.Intent
import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.material3.Button
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")
LaunchNewActivityButton()
}
}
}
}
}
@Composable
fun Greeting(name: String, modifier: Modifier = Modifier) {
Text(
text = "Hello $name!",
modifier = modifier
)
}
@Composable
fun LaunchNewActivityButton() {
Button(
onClick = {
val intent = Intent(
LocalContext.current,
NewActivity::class.java
)
startActivity(intent)
},
modifier = Modifier.padding(top = 16.dp)
) {
Text("Launch New Activity")
}
}
@Preview(showBackground = true)
@Composable
fun GreetingPreview() {
HandWritingTheme {
Greeting("Android")
}
}
```
在这个代码中,我们首先在onCreate()方法中添加了一个新的组件LaunchNewActivityButton(),它是在Material Design组件库中的Button组件的基础上实现的。在这个组件中,我们创建了一个新的Intent对象,指定了当前activity为MainActivity,目标activity为NewActivity,并启动了这个新的activity。您可以根据实际情况,修改NewActivity为您需要启动的目标activity的名称。
阅读全文