ora*_*nge 1 java optimization android code-duplication
我坚持如何减少代码重复,我使用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
}
});
}
Run Code Online (Sandbox Code Playgroud)
将TextToSpeech对象的创建提取到单独的函数中:
private TextToSpeech createTextToSpeech(final Locale loc) {
return new TextToSpeech(MainActivity.this,
new TextToSpeech.OnInitListener() {
@Override
public void onInit(int status) {
if (status != TextToSpeech.ERROR) {
setLanguage(loc);
}
}
});
}
Run Code Online (Sandbox Code Playgroud)
请注意,loc必须声明参数final,以便可以在匿名类中使用它.
用法:
...
} else if (parent.getItemAtPosition(pos).toString().equals("French")) {
textToSpeech = createTextToSpeech(Locale.FRANCE);
} ...
Run Code Online (Sandbox Code Playgroud)