当单击ImageButton时尝试发出声音时,我的应用程序崩溃了,并且我盯着我的代码已经有一段时间了,却找不到答案。我希望你们能帮助我看看我做错了什么。
我尝试使用imageButton手动使onClick事件失败,然后通过Eclipse的拖放系统对其进行了尝试,该过程使按钮可通过我通过main.xml命名为test123的方法单击。
我将发布我的代码,希望你们能找到解决方案。
提前致谢,
package com.example.Jeffrey;
import android.app.Activity;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
public class Jeffrey extends Activity {
MediaPlayer mp;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mp = MediaPlayer.create(this, R.raw.noise);
// View rakker = findViewById(R.id.imageView1);
//rakker.setOnClickListener(this);
}
public void test123()
{
mp.start();
}
}
代码附带的xml:
<ImageButton
android:src="@drawable/rakker"
android:layout_height="250px"
android:layout_width="wrap_content" android:id="@+id/imageView1"
android:onClick="test123"></ImageButton>
最佳答案
考虑到它由于某种原因而无法创建MediaPlayer对象,则返回一个空值可能值得检查。另外,它可能应该在完成时被释放(也带有空检查)。
编辑:
虽然我较早的答案可能值得考虑,但绝对有必要让您的onClick方法将“ View ”作为参数。
//at the top of the file
import android.view.View;
public void test123(View v){
//v is the view that has been clicked (the ImageButton from your .xml file)
//do stuff
}
关于android - 尝试播放声音时ImageButton崩溃,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7030037/