本文介绍了来自另一个类的getAssets()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述 29岁程序员,3月因学历无情被辞!public class CarnivoreFragment extends Fragment { private int mCowSound; private View view; private ImageButton mCowImageButton; public CarnivoreFragment() { } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { view = inflater.inflate(R.layout.fragment_carnivore, container, false); if (android.os.Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) { Sound.createOldSoundPool(); } else { Sound.createNewSoundPool(); } mCowSound = Sound.loadSound("cow.wav"); mCowImageButton = (ImageButton) view.findViewById(R.id.imageButtonCow); mCowImageButton.setOnClickListener(onClickListener); return view; } View.OnClickListener onClickListener = new View.OnClickListener() { @Override public void onClick(View v) { switch (v.getId()) { case R.id.imageButtonCow: Sound.playSound(mCowSound); Toast.makeText(view.getContext(), "Cow", Toast.LENGTH_SHORT).show(); break; } } };}public class Sound { private static SoundPool mSoundPool; private static AssetManager mAssetManager; private static int mStreamID; private static Context context; public Sound(Context context) { this.context = context; } @TargetApi(Build.VERSION_CODES.LOLLIPOP) public static void createNewSoundPool() { AudioAttributes attributes = new AudioAttributes.Builder() .setUsage(AudioAttributes.USAGE_GAME) .setContentType(AudioAttributes.CONTENT_TYPE_SONIFICATION) .build(); mSoundPool = new SoundPool.Builder() .setAudioAttributes(attributes) .build(); } @SuppressWarnings("deprecation") public static void createOldSoundPool() { mSoundPool = new SoundPool(3, AudioManager.STREAM_MUSIC, 0); } public static int playSound(int sound) { if (sound > 0) { mStreamID = mSoundPool.play(sound, 1, 1, 1, 0, 1); } return mStreamID; } public static int loadSound(String fileName) { mAssetManager = context.getAssets(); AssetFileDescriptor afd; try { afd = mAssetManager.openFd(fileName); } catch (IOException e) { e.printStackTrace(); Toast.makeText(context, "Не могу загрузить файл " + fileName, Toast.LENGTH_SHORT).show(); return -1; } return mSoundPool.load(afd, 1); }}推荐答案public static int loadSound(Context context, String fileName) { mAssetManager = context.getAssets(); .... } 并在片段内使用上下文and use context inside fragmentmCowSound = Sound.loadSound(getActivity(), "cow.wav"); 这篇关于来自另一个类的getAssets()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持! 上岸,阿里云! 07-22 16:17