首页 > 解决方案 > 如何在 Android Studio 中使用 Kotlin 中的 FAB 将用户发送到搜索页面?

问题描述

任何人都可以帮我处理这段代码吗?

p0.btnPlay.setOnClickListener {

    val songName = song.songName
    val songArtist = song.songArtist

    Toast.makeText(mCtx, "You clicked this button!", Toast.LENGTH_SHORT).show()

    val webIntent = Intent(Intent.ACTION_WEB_SEARCH, Uri.parse("https://www.youtube.com/results?search_query=$songArtist+$songName"))
    startActivity(webIntent)
}

我收到一个错误startActivity(webIntent):类型不匹配:推断类型是 Intent 但预期上下文

如何将用户发送到这样的 youtube 页面?toast 消息工作正常,因此按钮单击连接到 XML。

标签: androidkotlinandroid-intentfloating-action-button

解决方案


如果你mCtx是 Activity context,那么使用

try {
    val webIntent = Intent(Intent.ACTION_VIEW, Uri.parse("https://www.youtube.com/results?search_query=$songArtist+$songName"))
    mCtx.startActivity(webIntent)
} catch(ex: Exception) {
    ex.stackTrace
}

如果您在片段内,请尝试使用

try {
    val webIntent = Intent(Intent.ACTION_VIEW, Uri.parse("https://www.youtube.com/results?search_query=$songArtist+$songName"))
    activity!!.startActivity(webIntent)
} catch(ex: Exception) {
    ex.stackTrace
}

推荐阅读