【问题标题】:Toast message doesn't show up on actual phone while it shows in emulatorToast 消息在模拟器中显示时未显示在实际手机上
【发布时间】:2019-10-12 18:52:43
【问题描述】:

我正在尝试创建一个安卓应用程序。一部分是确保显示吐司消息。当我在 android studio 模拟器上运行应用程序时它可以工作,但是当我在实际的三星手机上运行时它不会显示

大约有一千行代码,所以我认为复制所有代码没有帮助。所以,我想知道是否有任何常见问题可以使 toast 消息显示在模拟器中,但不能显示在实际手机中。

-- 编辑--

这是我要祝酒的部分之一

private fun addListenerOnImageButtonHelper(intent: Intent, sensorId: Int, sensorType: Int, sensorTypeToString: String) {
    findViewById<ImageButton>(sensorId).setOnClickListener {
        if (sensorManager.getDefaultSensor(sensorType) != null) {
            intent.putExtra("sensor", sensorType)
            startActivity(intent)
        } else {
            Toast.makeText(this,
                "$sensorTypeToString sensor is not available on this device",
                Toast.LENGTH_LONG).show()
        }
    }
}

-- 编辑--

手机显示通知的设置已关闭。问题解决了...谢谢

【问题讨论】:

  • 请在此处粘贴您正在编写的代码以显示吐司。
  • 只粘贴一个发生的例子。我们不需要 1000 行代码
  • 兄弟在任何你想显示 Toast 的地方写下你的代码
  • Toast.makeText(ctx,message, Toast.LENGTH_SHORT).show()
  • 在 ctx 中传递 this@YourActivity.class

标签: android kotlin android-toast


【解决方案1】:

创建toast时需要添加ActivityName.this

因为你想从ImageButton显示toast点击

private fun addListenerOnImageButtonHelper(intent: Intent, sensorId: Int, sensorType: Int, sensorTypeToString: String) {
    findViewById<ImageButton>(sensorId).setOnClickListener {
        if (sensorManager.getDefaultSensor(sensorType) != null) {
            intent.putExtra("sensor", sensorType)
            startActivity(intent)
        } else {
            Toast.makeText(ActivityName.this,
                "$sensorTypeToString sensor is not available on this device",
                Toast.LENGTH_LONG).show()
        }
    }
}

否则,您需要在函数中将Context 作为参数传递

喜欢

private fun addListenerOnImageButtonHelper(context: Context,intent: Intent, sensorId: Int, sensorType: Int, sensorTypeToString: String) {
    findViewById<ImageButton>(sensorId).setOnClickListener {
        if (sensorManager.getDefaultSensor(sensorType) != null) {
            intent.putExtra("sensor", sensorType)
            startActivity(intent)
        } else {
            Toast.makeText(context,
                "$sensorTypeToString sensor is not available on this device",
                Toast.LENGTH_LONG).show()
        }
    }
}

【讨论】:

  • 当我将其更改为 MainPageActivity.this 时会导致错误(红线)(活动名称为 MainPageActivity)
  • @Vishal Sojitra No!
  • ActivityName.this 不是必需的!
  • 你也可以使用context
  • 我刚试过 applicationContext 但它不起作用
猜你喜欢
  • 2021-06-18
  • 2015-02-12
  • 1970-01-01
  • 2017-04-04
  • 2014-09-21
  • 1970-01-01
  • 1970-01-01
  • 2011-12-09
相关资源
最近更新 更多