当我尝试在setonclicklistener中调用方法loadSound时,声音不会出现,但是当我在onCreateView或onStart方法中调用它时,声音会出现,一切正常。 有什么问题 ? 有没有办法只在按下按钮时调用方法??
甚至我在setonclicklistener方法中调用了方法setOnLoadCompleteListener,但仍然没有帮助。
public class InsectsFragment extends Fragment {
private View view;
private int mBeeSound;
public InsectsFragment() {
// Required empty public constructor
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
view= inflater.inflate(R.layout.fragment_insects, container, false);
Sound.mSoundPool.setOnLoadCompleteListener(new SoundPool.OnLoadCompleteListener() {
@Override
public void onLoadComplete(SoundPool soundPool, int sampleId, int status) {
Sound.loaded = true;
}
});
ImageButton beeBtn = (ImageButton) view.findViewById(R.id.imageButtonBee);
beeBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (Sound.mStreamID > 0) {
Sound.mSoundPool.stop(Sound.mStreamID);
}
mBeeSound = Sound.loadSound(getContext(), "bee.mp3");
if (Sound.loaded) {
Sound.playSound(mBeeSound);
Snackbar.make(view, R.string.Bee, Snackbar.LENGTH_SHORT).show();
Toast.makeText(view.getContext(), R.string.Bee, Toast.LENGTH_SHORT).show();
}
}
});
return view;
}
答案 0 :(得分:0)
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
view= inflater.inflate(R.layout.fragment_insects, container, false);
ImageButton beeBtn = (ImageButton) view.findViewById(R.id.imageButtonBee);
beeBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (Sound.mStreamID > 0) {
Sound.mSoundPool.stop(Sound.mStreamID);
}
Sound.mSoundPool.setOnLoadCompleteListener(new SoundPool.OnLoadCompleteListener() {
@Override
public void onLoadComplete(SoundPool soundPool, int sampleId, int status) {
Sound.loaded = true;
if (Sound.loaded) {
Sound.playSound(mBeeSound);
Snackbar.make(view, R.string.Bee, Snackbar.LENGTH_SHORT).show();
Toast.makeText(view.getContext(), R.string.Bee, Toast.LENGTH_SHORT).show();
}
}
});
mBeeSound = Sound.loadSound(getContext(), "bee.mp3");
}
});
return view;
}

答案 1 :(得分:0)
确保将正确的上下文传递给soundpool。在setclicklistener中,您可能正在传递侦听器的上下文。