导入我的自定义类并调用它的方法?

Ham*_*mid 5 import android class

我为我的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;
}
}
Run Code Online (Sandbox Code Playgroud)

在我的主Activity类中,我尝试导入类,创建它的实例,但我想我只是不理解它是如何完成的.有人能指出我正确的方向吗?

Wro*_*lai 9

编辑:来自你的Activity班级:

private Sounds s;

@Override
protected void onCreate(Bundle savedInstanceState) {
     super.onCreate(savedInstanceState);        
        s = new Sounds(this);
        s.initSounds();
}
Run Code Online (Sandbox Code Playgroud)

您还可以将带有构造函数的上下文发送到自定义类.

删除静态变量和方法:

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;
}
}
Run Code Online (Sandbox Code Playgroud)