android - 通过单击按钮播放声音
问题描述
我在运行代码时遇到问题,即通过使用 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 代码是不完整的,因为在我尝试了很多之后我无法做到。如果你能做到,你能告诉我你是怎么做到的吗?谢谢你
解决方案
尝试像这样实现按钮
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
}
推荐阅读
- json - 从大数据库中将数据从 api 提取到 excel
- python - Pandas - 两列作为索引(有效时间和行号)?
- javascript - How to use Modulo inside of a forEach loop using arrow function?
- java - 使用预定的 powershell 运行 jar 文件并验证结果
- spring-cloud-stream - 即使 Kakfa 宕机也能启动应用程序
- python - How to find an array in string format in pandas using regular expression?
- kotlin - 在 Kotlin 中对可否决的代表进行空检查
- php - 如何计算总 PHP dateInterval 并以日期、月份、年份显示结果
- amazon-web-services - AWS CloudFormation 是否支持 AWS::EC2::VPCEndpoint 的标签属性属性
- javascript - 如何在 Angular8 中加载 JS 文件