1
我的MainFragment中有多個字符串變量和EditText變量。對於所有的EditText,我希望我的字符串變量在EditText的文本更改後得到assigend值。目前我是這樣做的:android TextWatcher更改外部專用字段
private String itemName;
private String itemNumber;
private EditText itemNameET;
private EditText itemNumberET;
private void initEditTexts() {
itemName = itemNameET.getText().toString();
itemNumber = itemNumberET.getText().toString();
itemNameET.addTextChangedListener(new TextWatcher() {
@Override
public void afterTextChanged(Editable s) {
itemName = (String) s.toString();
}
@Override
public void beforeTextChanged(CharSequence arg0, int arg1,
int arg2, int arg3) {}
@Override
public void onTextChanged(CharSequence s, int start, int before,
int count) {}
});
itemNumberET.addTextChangedListener(new TextWatcher() {
@Override
public void afterTextChanged(Editable s) {
itemNumber = (String) s.toString();
}
@Override
public void beforeTextChanged(CharSequence arg0, int arg1,
int arg2, int arg3) {}
@Override
public void onTextChanged(CharSequence s, int start, int before,
int count) {}
});
我想嘗試刪除冗餘代碼,因爲我在活動中有很多EditTexts。我在考慮去一起創建CustomTextWatcher:
public class CustomTextWatcher implements TextWatcher {
private String text;
public CustomTextWatcher(String text) {
this.text = text;
}
@Override
public void afterTextChanged(Editable s) {
text = (String) s.toString();
}
@Override
public void beforeTextChanged(CharSequence arg0, int arg1,
int arg2, int arg3) {}
@Override
public void onTextChanged(CharSequence s, int start, int before,
int count) {}
}
但那麼這將無法工作,因爲變量在OuterClass仍然沒有分配新的價值,因爲它是通過按值。我如何在Java中做一些具有傳遞引用效果的東西,或者我可以採取什麼其他方式將外部類變量傳遞給內部類,並且該變量可以在內部類中更新?