我目前有以下代码,从A开始一直到Z:
if (someId.matches("A") || someId.matches("a")) {
tvLetCap.setText("A");
tvLetLow.setText("a");
ivLetterIcon.setImageResource(R.drawable.apple);
btnDisplayWord.setText("A is for APPLE");
btnPlay.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
stopPlaying();
mpSound = MediaPlayer.create(MyClass.this, R.raw.a);
mpSound.setLooping(false);
mpSound.start();
btnPlay.setVisibility(View.GONE);
btnStop.setVisibility(View.VISIBLE);
btnStop.setOnClickListener(stopSound);
mpSound.setOnCompletionListener(new OnCompletionListener() {
@Override
public void onCompletion(MediaPlayer mp) {
btnPlay.setVisibility(View.VISIBLE);
btnStop.setVisibility(View.GONE);
}
});
}
});
}
if (someId.matches("B") || someId.matches("b")) {
tvLetCap.setText("B");
tvLetLow.setText("b");
ivLetterIcon.setImageResource(R.drawable.ball);
btnDisplayWord.setText("B is for BALL");
btnPlay.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
stopPlaying();
mpSound = MediaPlayer.create(MyClass.this, R.raw.b);
mpSound.setLooping(false);
mpSound.start();
btnPlay.setVisibility(View.GONE);
btnStop.setVisibility(View.VISIBLE);
btnStop.setOnClickListener(stopSound);
mpSound.setOnCompletionListener(new OnCompletionListener() {
@Override
public void onCompletion(MediaPlayer mp) {
btnPlay.setVisibility(View.VISIBLE);
btnStop.setVisibility(View.GONE);
}
});
}
});
}
这是否与上述相反:
switch(someId) {
case A:
setLetter("A");
addIcon("apple");
break;
case B:
setLetter("B");
addIcon("ball");
break;
default:
break;
}
public void setLetter(String strLetter) {
tvLetCap.setText(strLetter);
tvLetLow.setText(strLetter.toLowerCase());
}
public void addIcon(String iconLetter) {
ivLetterIcon.setImageResource(R.drawable. + iconLetter);
btnDisplayWord.setText(iconLetter.charAt(0).toUpperCase() + " is for " + iconLetter.toUpperCase());
}
我猜唯一的问题可能是这条线,我该如何解决它?:
ivLetterIcon.setImageResource(R.drawable. + iconLetter);
另外,是否可以将整个 btnPlay
函数传递给另一个函数,然后像我对其他函数所做的那样传递字母,这样就不会重复?
最佳答案
我不知道R
和R.drawable
是什么;什么是R.drawable.apple
、R.drawable.ball
等?假设它们都具有相同的类型,您可能希望将 R.drawable 设为一个数组,其中索引为 0 表示“A”,1 表示“B”等,并初始化它以便 R .drawable[0] =(无论“苹果”应该是什么),R.drawable[1] =(与“球”相同);然后使用类似
R.drawable[someId.charAt(0).toUpperCase() - 'A']
对于R.raw
也类似。那么您根本就不需要开关
。
kcoppock 编辑:
例如:
int[] icons = {
R.drawable.a,
R.drawable.b,
//etc.
};
int[] sounds = {
R.raw.a,
R.raw.b,
//etc.
}
并使用icons[index]
和sounds[index]
来映射您的值。
关于java - 通过消除额外的代码使应用程序更加高效,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18412055/