我正在开发 Android 应用程序。一切似乎都运行良好,但我想让我的代码比现在更短。您可能会认为很多行都是重复的:
public void ButtonKlick (View view) {
double zahl1;
double zahl2;
double zahl3;
double zahl4;
double Ergebnis = 0;
EditText Feld1 = (EditText)findViewById(R.id.zahl1);
EditText Feld2 = (EditText)findViewById(R.id.zahl2);
EditText Feld3 = (EditText)findViewById(R.id.zahl3);
EditText Feld4 = (EditText)findViewById(R.id.zahl4);
EditText FeldErgebnis = (EditText)findViewById(R.id.etErgebnis);
if (Feld1.getText().toString().length() == 0 ) {
return;
}
if (Feld2.getText().toString().length() == 0 ) {
return;
}
if (Feld3.getText().toString().length() == 0 ) {
return;
}
if (Feld4.getText().toString().length() == 0 ) {
return;
}
zahl1 = Double.parseDouble(Feld1.getText().toString());
zahl2 = Double.parseDouble(Feld2.getText().toString());
zahl3 = Double.parseDouble(Feld3.getText().toString());
zahl4 = Double.parseDouble(Feld4.getText().toString());
Ergebnis = Math.sqrt(Math.pow(zahl4 - zahl3, 2) + Math.pow(zahl2 - zahl1, 2));
FeldErgebnis.setText(String.valueOf(Ergebnis));
}
这两种方法都始于:
double zahl1;
到
zahl4 = Double.parseDouble(Feld4.getText().toString());
是否有任何特定的方法可以摆脱这些相同的线条?
最佳答案
编写一个实用方法,如:
private double getDouble(EditText tv) {
return Double.parseDouble(tv.getText().toString());
}
并这样调用它:
zahl4 = getDouble(Field4);
编辑:
private double getDouble(int viewId) {
View view = findViewById(viewId);
double toReturn = 0;
// instanceOf returns false for null values
if (view instanceOf EditText)
toReturn = Double.parseDouble(view.getText().toString());
return toReturn;
}
关于Java:如何缩短经常使用的代码?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16318706/