代码之家  ›  专栏  ›  技术社区  ›  Hamid

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

  •  5
  • Hamid  · 技术社区  · 14 年前

    我已经为我的Android项目创建了一个名为“声音”的自定义类,我希望能够从我的活动中调用它。我班的内容如下:

    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;
    }
    }
    

    在我的主活动类中,我尝试导入该类,创建它的实例,但我想我只是不理解它是如何完成的。有人能给我指个方向吗?

    4 回复  |  直到 12 年前
        1
  •  9
  •   Wroclai    14 年前

    Activity

    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;
    }
    }
    
        2
  •  2
  •   malagas    12 年前

    Private JavaScriptInterface myJavaScriptInterface;
    myJavaScriptInterface.Toastshow("Hi EveryOne");
    

    JavaScriptInterface myJavaScriptInterface = new JavaScriptInterface(this);
    

     public class JavaScriptInterface {
    
        Context myContext;
    
        //Instanciar o interface e definir o conteudo 
        JavaScriptInterface(Context c) {
            myContext = c;
        }
    
    
        public void Toastshow(String toast_msg)
        {
    
    
            Toast.makeText(myContext, toast_msg, Toast.LENGTH_LONG).show();
        }
    }
    

        3
  •  1
  •   Shane Oliver    14 年前

    Sounds s = new Sounds();
    s.initSounds();
    s.playFlip();
    s.setSound(true);
    
        4
  •  1
  •   Jess    14 年前

    Sounds.initSound() static FLIP_SOUND