我为我的 Android 项目创建了一个名为“Sounds”的自定义类,我希望能够从我的活动中调用它。我的课内容如下:
package com.mypackage;
import java.util.HashMap;
import android.content.Context;
import android.media.SoundPool;
public class Sounds {
private static boolean sound = true;
private static final int FLIP_SOUND = 1;
private static Context context;
private static SoundPool soundPool;
private static HashMap<Integer, Integer> soundPoolMap;
public static void initSounds() {
soundPoolMap.put(FLIP_SOUND, soundPool.load(context, R.raw.flip, 1));
}
public static void playFlip() {
soundPool.play(soundPoolMap.get(FLIP_SOUND), 1, 1, 1, 0, 1);
}
public static void setSound(Boolean onOff) {
sound = onOff;
}
}
在我的主 Activity 类中,我尝试导入该类,创建它的实例,但我想我只是不明白它是如何完成的。有人能指出我正确的方向吗?
编辑:来自你的Activity
class:
private Sounds s;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
s = new Sounds(this);
s.initSounds();
}
您还可以将带有构造函数的上下文发送到您的自定义类。
删除静态变量和方法:
public class Sounds {
private boolean sound = true;
private int FLIP_SOUND = 1;
private Context context;
private SoundPool soundPool;
private HashMap soundPoolMap;
public Sounds(Context context){
this.context = context;
soundPoolMap = new HashMap();
soundPool = new SoundPool(0, AudioManager.STREAM_MUSIC, 0);
}
public void initSounds() {
soundPoolMap.put(FLIP_SOUND, soundPool.load(context, R.raw.flip, 1));
}
public void playFlip() {
soundPool.play(soundPoolMap.get(FLIP_SOUND), 1, 1, 1, 0, 1);
}
public void setSound(Boolean onOff) {
sound = onOff;
}
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)