我正在创建一个简单的应用程序,当按钮被点击时,会显示一条祝wine 词消息.但当点击该按钮时,不会显示祝wine 词消息.

这是我的mainActivity和activityMain.xml代码.

package com.example.myapplication2

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.Button
import android.widget.Toast

class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        val clickMeButton = findViewById<Button>(R.id.toast_button)

        clickMeButton.setOnClickListener {
            Toast.makeText(applicationContext, "Toast Message", Toast.LENGTH_LONG).show()
        }
    }
}
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout

    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <Button
        android:id="@+id/toast_button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Click Me!"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>

推荐答案

您应该使用活动上下文,但您使用的是应用程序上下文(请参见Difference between Activity Context and Application Context).您应该使用以下代码更新代码:

Toast.makeText(this, "Toast Message", Toast.LENGTH_LONG).show()

Android相关问答推荐

Android模拟器:无法安装ShellCommandUnresponsiveResponse和UtpResponse异常

使用Kotlin的SD卡

使用Kotlin/Compose与Java/XML指南的比较

如何从Android 12的来电中获取电话号码?

安卓喷气背包组成倒计时动画

将DiffUtils用于Android上的Recrecerview适配器

ERR_SSL_VERSION_OR_CIPHER_MISMATCH - Android Webview

如何在DownloadManager Android中显示ProgressBar和Complete Listener

设置文本 colored颜色 动画时如何减少重新组合?

Android 中 recyclerview 的自定义分隔线 colored颜色 不起作用

需要 java 17 而不是 java 11:Android CI-CD GitHub Actions

如何在我的sqlite数据库中获取某个玩家的分数

尽管我在onCreate()期间已经初始化,但仍出现未初始化的late init变量错误

当 EditText 用于在 android studio 中将字符串发送到 firebase 时,仅允许安全调用错误

Kotlin 协程、 retrofit 、android

在 Jetpack Compose 中自动滚动后面的项目

如何使用 Jetpack Compose 制作两个圆圈

插入查询室 OnConflictStrategy.REPLACE

当我更改 ViewModel var 时,Kotlin + Compose 中的 Composable 不会更新

基线配置文件 x R8/Proguard