我希望在点击文本时播放某个 mp3 文件。例如,当我点击“Nicholas”这个词时,应用程序就要播放 nicholas.mp3 文件。
对于我的混乱代码表示抱歉,我是 Android 开发的新手:
package com.example.playword;
import java.io.IOException;
import android.app.Activity;
import android.media.MediaPlayer;
import android.os.Bundle;
//import android.os.Handler;
import android.view.View;
//import android.view.View.OnClickListener;
//import android.widget.Button;
import android.widget.TextView;
public class PlayWord extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
//final Handler mHandler = new Handler();
final TextView nicholas = (TextView) findViewById(R.id.nicholas);
final TextView was = (TextView) findViewById(R.id.was);
nicholas.setText("Nicholas ");
was.setText("was ");
/*
Button btn = (Button) (findViewById(R.id.nicholasBtn));
btn.setOnClickListener(new OnClickListener(){
@Override
public void onClick(View v) {
nicholas.setText("Nicholas (Clicked!) ");
}
});
*/
View.OnClickListener handler = new View.OnClickListener(){
public void onClick(View v) {
switch (v.getId()) {
case R.id.nicholas: // doStuff
MediaPlayer mPlayer = MediaPlayer.create(null, R.raw.aaanicholas);
try {
mPlayer.prepare();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
mPlayer.start();
nicholas.setText("Nicholas (Clicked!) ");
break;
case R.id.was: // doStuff
MediaPlayer mPlayer1 = MediaPlayer.create(null, R.raw.aaawas);
try {
mPlayer1.prepare();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
mPlayer1.start();
was.setText("was (Clicked!) ");
break;
}
}
};
findViewById(R.id.nicholas).setOnClickListener(handler);
findViewById(R.id.was).setOnClickListener(handler);
}
}
运行时,我得到了一个强制关闭错误。您对此有更好的想法吗?