我有许多声音按级别组织,level1explicacio2,level2explicacio8等。有时这种声音会存在有时不存在。所以我需要检查是否存在,例如 level5explicacio3,如果存在,则播放一些动画。所以我做了一个if检查levelSoundPlayer是否为空,但当然,它不会编译,因为它找不到levelSoundPlayer的资源。我该如何解决这个问题?
levelSound = "level" + sharedPreferences.getString("Level","1") + "explicacio" + Integer.toString(1);
Log.i("aviam", levelSound);
levelSoundPlayer = MediaPlayer.create(this, getResources().getIdentifier(levelSound, "raw", getPackageName()));
imageView = findViewById(R.id.imageView);
imageViewReplace = findViewById(R.id.imageViewReplace);
if (levelSoundPlayer!=null){
Animation a = new AlphaAnimation(1.00f, 0.00f);
a.setRepeatMode(Animation.REVERSE);
a.setRepeatCount(Animation.INFINITE);
a.setDuration(1000);
imageViewReplace.startAnimation(a);
}
您可以从他们的标识符中检查它,如下所示
levelSound = "level" + sharedPreferences.getString("Level","1") + "explicacio" + Integer.toString(1);
Log.i("aviam", levelSound);
levelSoundPlayer = MediaPlayer.create(this, getResources().getIdentifier(levelSound, "raw", getPackageName()));
imageView = findViewById(R.id.imageView);
imageViewReplace = findViewById(R.id.imageViewReplace);
int valId = getResources().getIdentifier(levelSound, "raw", getPackageName());
if (valId != 0){
Animation a = new AlphaAnimation(1.00f, 0.00f);
a.setRepeatMode(Animation.REVERSE);
a.setRepeatCount(Animation.INFINITE);
a.setDuration(1000);
imageViewReplace.startAnimation(a);
}
在 https://developer.android.com/reference/android/content/res/Resources 文件中还说
int 关联的资源标识符。如果没有此类资源,则返回 0 被发现了。(0 不是有效的资源 ID。