我被困在如何減少此代碼重複,我使用TextToSpeech引擎和使用語言環境,以便用戶可以選擇他們的語言。如何減少此代碼重複
language
是一個微調。
language.setOnItemSelectedListener(new OnItemSelectedListener() {
public void onItemSelected(AdapterView<?> parent, View arg1,
int pos, long id) {
System.out.println(parent.getItemAtPosition(pos).toString());
if (parent.getItemAtPosition(pos).toString().equals("UK")) {
textToSpeech = new TextToSpeech(MainActivity.this,
new TextToSpeech.OnInitListener() {
@Override
public void onInit(int status) {
if (status != TextToSpeech.ERROR) {
textToSpeech.setLanguage(Locale.UK);
}
}
});
} else if (parent.getItemAtPosition(pos).toString()
.equals("US")) {
textToSpeech = new TextToSpeech(MainActivity.this,
new TextToSpeech.OnInitListener() {
@Override
public void onInit(int status) {
if (status != TextToSpeech.ERROR) {
textToSpeech.setLanguage(Locale.US);
}
}
});
} else if (parent.getItemAtPosition(pos).toString()
.equals("French")) {
textToSpeech = new TextToSpeech(MainActivity.this,
new TextToSpeech.OnInitListener() {
@Override
public void onInit(int status) {
if (status != TextToSpeech.ERROR) {
textToSpeech.setLanguage(Locale.FRANCE);
}
}
});
} else if (parent.getItemAtPosition(pos).toString()
.equals("Italian")) {
textToSpeech = new TextToSpeech(MainActivity.this,
new TextToSpeech.OnInitListener() {
@Override
public void onInit(int status) {
if (status != TextToSpeech.ERROR) {
textToSpeech
.setLanguage(Locale.ITALIAN);
}
}
});
} else if (parent.getItemAtPosition(pos).toString()
.equals("German")) {
textToSpeech = new TextToSpeech(MainActivity.this,
new TextToSpeech.OnInitListener() {
@Override
public void onInit(int status) {
if (status != TextToSpeech.ERROR) {
textToSpeech
.setLanguage(Locale.GERMAN);
}
}
});
}
}
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
});
}
也許你應該嘗試[codereview.se(http://codereview.stackexchange.com) –
我真的很感激我得到了答案,但爲什麼請求關閉這個問題?爲什麼不讓我知道我在這裏發佈了這個問題,所以我可以學習? – orange
堆棧溢出是針對破損的代碼,Codereview是針對次優設計的工作代碼 –