如何在Android中的选择单选按钮选项上播放声音

时间:2016-12-30 17:25:43

标签: android

当用户在选项铃声播放时选择以下字符串..

在与单选按钮对话框中显示的字符串:

final CharSequence[] items = {" Default", " Vibration", " Best awake ", " Elegent Ringtone " , "Digital phone"};

1 个答案:

答案 0 :(得分:0)

1.将您的声音文件保存在一个数组中。定义一个数组说"音乐"全局。

int[] music ;

2.在您的活动(或片段)中实现DialogInterface.OnClickListener

3.在OnCreate中初始化声音阵列和标题数组并创建单选警告对话框

final CharSequence[] items = {" Default", " Vibration", " Best awake ", " Elegent Ringtone " , "Digital phone"};
music = new int[]{R.raw.one,R.raw.two,R.raw.three,R.raw.four,R.raw.five};

    AlertDialog.Builder builder = new AlertDialog.Builder(this);
    builder.setPositiveButton("OK",this);
    builder.setNegativeButton("Cancel",this);
    builder.setTitle("Choose Sound");
    builder.setSingleChoiceItems(items,-1,this);
    builder.create();
    builder.show();

4.您对DialogInterface.OnClickListener的看法应该看起来应该是这样的

 @Override
public void onClick(DialogInterface dialogInterface, int position) {
  switch (position){
      case DialogInterface.BUTTON_POSITIVE :
          //Do your stuffs
          dialogInterface.dismiss();
          break;
      case DialogInterface.BUTTON_NEGATIVE:
          //Do your stuffs
          dialogInterface.dismiss();
          break;
      default: //Single choice item selected
          playSound(music[position]);
          break;
  }
}

5. playound方法将是这样的

private void playSound(int res) {
    MediaPlayer mediaPlayer = MediaPlayer.create(this,res);
    mediaPlayer.start();
}