没有必要发明轮子。Android 框架为此提供了小部件 - NumberPicker。
编辑:如果你不能或不想使用NumberPicker
,这里的想法是:
private class NumberPicker {
private int value=0;
private Button btnIncr;
private Button btnDecr;
private EditText editText;
public NumberPicker(Button btnIncr, Button btnDecr, EditText editText) {
this.btnIncr=btnIncr;
this.btnDecr=btnDecr;
this.editText=editText;
this.btnIncr.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
value++;
NumberPicker.this.editText.setText(String.valueOf(value));
}
});
this.btnDecr.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
value--;
NumberPicker.this.editText.setText(String.valueOf(value));
}
});
editText.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
value=Integer.parseInt(s.toString());
}
@Override
public void afterTextChanged(Editable s) {
}
});
}
public int getValue() {
return value;
}
}
并且不要担心当按钮更改值时会触发 TextWatcher。这不应该引起任何问题。