我看过其他一些问题和帖子,但是似乎无法弄清楚……我正在构建一个转换应用程序,可以通过使用addTextChangedListener插入英寸来自动填充Feet和Yards,但是我无法弄清楚如何将TextChangedListener添加到其他字段,以便我可以输入Feet并自动将其转换为Inches and Yards,以及将Yards转换为Inches and Feet ...
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final EditText editIn = (EditText) findViewById(R.id.editIn);
final EditText editFt = (EditText) findViewById(R.id.editFt);
final EditText editYd = (EditText) findViewById(R.id.editYd);
editIn.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence charSequence, int i, int i2, int i3) { }
@Override
public void onTextChanged(CharSequence charSequence, int i, int i2, int i3) {
try {
double in = Double.valueOf(editIn.getText().toString());
double ft = in / 12;
double yd = in / 36;
editFt.setText(String.valueOf(ft));
editYd.setText(String.valueOf(yd));
} catch (NumberFormatException e) {
e.printStackTrace();
}
}
@Override
public void afterTextChanged(Editable editable) { }
最佳答案
TextWatcher watcher = new TextWatcher() {
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
//YOUR CODE
}
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
//YOUR CODE
}
@Override
public void afterTextChanged(Editable s) {
//YOUR CODE
}
};
editIn.addTextChangedListener(watcher);
editFt.addTextChangedListener(watcher);
editYd.addTextChangedListener(watcher);