所以我在Android上制作了这个星球大战粉丝应用程序。
我有这个Yoda的形象和他的按钮。当你点击它时,现在他说一句话(与媒体播放器)。 问题是,我希望他说不同的东西,所以我有4个不同的MP3文件,但是当用户点击按钮时,如何让它随机选择哪个播放?
这是我现在的代码:
package be.ehb.arnojansens.simpleFrag;
import android.app.Activity;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
import be.ehb.arnojansens.fragmentexampleii.R;
public class SimpleFragmentActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_simple_fragment);
final Button advice = (Button) findViewById(R.id.YodaAdvice);
final MediaPlayer mp = MediaPlayer.create(this, R.raw.yodamessage);
advice.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Toast.makeText(getApplicationContext(), "Hmm Busy I Am", Toast.LENGTH_LONG).show();
mp.start();
}
});
}
}
答案 0 :(得分:1)
你可以有4条最终消息
final MediaPlayer mp = MediaPlayer.create(this, R.raw.yodamessage);
final MediaPlayer mp1 = MediaPlayer.create(this, R.raw.yodamessage1);//File names would be different I guess
final MediaPlayer mp2 = MediaPlayer.create(this, R.raw.yodamessage2);
final MediaPlayer mp3 = MediaPlayer.create(this, R.raw.yodamessage3);
你还需要随机
Random random=new Random();
然后在你的点击方法
int r = random.nextInt(4);
if(r==0){
mp.start();
Toast.makeText(getApplicationContext(), "Hmm Busy I Am", Toast.LENGTH_LONG).show();
}
if(r==1){
mp1.start();
Toast.makeText(getApplicationContext(), "I'm hungry", Toast.LENGTH_LONG).show();
}
if(r==2){
mp2.start();
Toast.makeText(getApplicationContext(), "My droid now", Toast.LENGTH_LONG).show();
}
if(r==3){
mp3.start();
Toast.makeText(getApplicationContext(), "Not droid you are looking for", Toast.LENGTH_LONG).show();
}