问题描述
我创建了此函数,以使按钮在单击时发出声音,声音文件为 public static void main(String[] args) {
String s="a a a b c c d d d d e e e e e";
int max=0;
String maxs="";
List<String> three= new ArrayList<String>();
HashMap<String,Integer > top= new HashMap<String,Integer> ();
for(String i : s.split(" ")){
if(top.containsKey(i)) {
top.replace(i,top.get(i)+1);
}
else {
top.put(i,1);
}
}
for(int i=0; i<=2;i++) {
max=0;
maxs="";
for(String j: top.keySet()) { //string(word):all the values together
if(top.get(j)> max ) {
max=top.get(j);
maxs=j;
}
}
three.add(maxs);
top.remove(maxs);
}
}
}
}
目录中的mp3。
raw/button_click.mp3
但是运行fun play_sound(which_one:Int) {
if(which_one == 1){
val mediaPlayer:MediaPlayer? = MediaPlayer.create(Context,R.raw.button_click)
mediaPlayer?.start()
}
}
我应该如何编辑代码来解决此问题?
顺便说一下,现在暂时忽略if语句,在开发的这个阶段它始终变为真。
解决方法
未解决的参考:上下文
由于使用类而不是变量名称作为参数,因此收到以下错误消息。
fun play_sound(which_one:Int) {
if(which_one == 1) {
val mediaPlayer:MediaPlayer? = MediaPlayer.create(Context,R.raw.button_click)
mediaPlayer?.start()
}
}
Android中还存在另一种 Context 。
您拥有自己的“应用程序”,“活动”和“片段上下文”,这些上下文也取决于您所使用的 Context 的不同生命周期。
如果此功能是您的活动的成员。
fun play_sound(which_one:Int) {
if(which_one == 1) {
val mediaPlayer:MediaPlayer? = MediaPlayer.create(this@YourActivityHere,R.raw.button_click)
mediaPlayer?.start()
}
}
片段
fun play_sound(which_one:Int) {
if(which_one == 1) {
val mediaPlayer:MediaPlayer? = MediaPlayer.create(requireContext(),R.raw.button_click)
mediaPlayer?.start()
}
}
,
将适当的有效Context
传递给此方法
fun play_sound(ctx:Context,which_one:Int) {
if(which_one == 1){
val mediaPlayer:MediaPlayer? = MediaPlayer.create(ctx,R.raw.button_click)
mediaPlayer?.start()
}
}