Issue
I have simple button in android jetpack compose, when I click the button, I want to open gmail and send mail to "[email protected]", is it possible?
@Composable
fun SimpleButton() {
Button(onClick = {
//your onclick code here
}) {
Text(text = "Simple Button")
}
}
Solution
You have to create an Intent and then start an Activity with it, similar to how you would have to do it normally.
The only difference in Compose is that you obtain the Context
with LocalContext.current
.
@Composable
fun SimpleButton() {
val context = LocalContext.current
Column {
Button(onClick = {
context.sendMail(to = "[email protected]", subject = "Some subject")
}) {
Text(text = "Send mail")
}
Button(onClick = {
context.dial(phone = "12345678")
}) {
Text(text = "Dial number")
}
}
}
fun Context.sendMail(to: String, subject: String) {
try {
val intent = Intent(Intent.ACTION_SEND)
intent.type = "vnd.android.cursor.item/email" // or "message/rfc822"
intent.putExtra(Intent.EXTRA_EMAIL, arrayOf(to))
intent.putExtra(Intent.EXTRA_SUBJECT, subject)
startActivity(intent)
} catch (e: ActivityNotFoundException) {
// TODO: Handle case where no email app is available
} catch (t: Throwable) {
// TODO: Handle potential other type of exceptions
}
}
fun Context.dial(phone: String) {
try {
val intent = Intent(Intent.ACTION_DIAL, Uri.fromParts("tel", phone, null))
startActivity(intent)
} catch (t: Throwable) {
// TODO: Handle potential exceptions
}
}
For more possibilities see answers here, but keep in mind that some are outdated.
Answered By - Ma3x
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.