首页 > 解决方案 > 通过单击按钮播放声音

问题描述

我在运行代码时遇到问题,即通过使用 kotlin 在 android studio 中单击按钮来运行声音。

XML

<LinearLayout 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"
    android:orientation="vertical"
    tools:context=".MainActivity">
    <Button
        android:id="@+id/gun"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginHorizontal="130dp"
        android:text="gun" />
</LinearLayout>

Kotlin 代码

override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
val buttonomega = findViewById<View>(R.id.gun) as Button
        mediaPlayer=MediaPlayer.create(this,R.raw.gunfire)
        val playBlownose = findViewById<View>(R.id.gun)

 buttonomega.setOnClickListener{

        }

注意:kotlin 代码是不完整的,因为在我尝试了很多之后我无法做到。如果你能做到,你能告诉我你是怎么做到的吗?谢谢你

标签: androidkotlin

解决方案


尝试像这样实现按钮

   override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        mediaPlayer=MediaPlayer.create(this,R.raw.gunfire)
        val playBlownose = findViewById<View>(R.id.)

 gun.setOnClickListener{
// do your work here
        }

推荐阅读