我有用于更改按钮onclick的图像的代码,然后在3秒后将其还原 . 点击时它也会发出声音 .
package com.example.btn;
import android.app.Activity;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
public class MainActivity extends Activity {
Handler mHandler; // global instance
Runnable your_runnable; // global instance
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void yolo(final View view) {
if (view == view) {
view.setBackgroundResource(R.drawable.btn1);//Change to this when clicked
final MediaPlayer mp1=MediaPlayer.create(getBaseContext(), R.raw.z);//this mp3 is compulsary
final MediaPlayer mp1=MediaPlayer.create(getBaseContext(), R.raw.r);//this mp3 should be random
mp1.start(); //play mp3
mHandler = new Handler();
your_runnable = new Runnable() {
@Override
public void run() {
view.setBackgroundResource(R.drawable.btn2);//Revert back to this after timer
}
};
mHandler.postDelayed(your_runnable, 3000L);// 3sec timer
}
}
}
我想要的是在点击该按钮时播放随机音乐,而不仅仅是播放指定的音乐 . (在这行最后的MediaPlayer mp1 = MediaPlayer.create(getBaseContext(),R.raw.r); //这个mp3应该是随机的)
我认为有两种方法可以实现这一点:1 . 从特定文件夹中随机播放音乐 . 2.通过代码从指定的音乐中随机播放音乐 .
请帮我解决一下这个 .
1 回答
将所有音乐资源ID放在一个数组中,然后随机选择一个播放,如下所示: