注意點,只有當結束變化時才去通知另一控件,不然會形成死循環
public class MainActivity extends AppCompatActivity {
private WheelView mWheelView;//游標控件
private EditText mMoneyEt;//金額輸入框
private int unitValue = 100;
private int maxValue = 100000;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mWheelView = (WheelView) findViewById(R.id.wheelview);
mMoneyEt = (EditText) findViewById(R.id.et_money);
final List<String> items = new ArrayList<>();
for (int i = 0; i <= maxValue / unitValue; i++) {
items.add(String.valueOf(i * unitValue));
}
mWheelView.setItems(items);
mMoneyEt.setText(String.format("%1$s", ""));
mWheelView.setOnWheelItemSelectedListener(new WheelView.OnWheelItemSelectedListener() {
@Override
public void onWheelItemSelected(WheelView wheelView, int position) {
String valueStr = wheelView.getItems().get(position);
mMoneyEt.setText(String.format("%1$s", valueStr));
}
@Override
public void onWheelItemChanged(WheelView wheelView, int position) {
}
});
setPricePoint(mMoneyEt, maxValue);
}
public void setPricePoint(final EditText editText, final float max) {
editText.addTextChangedListener(new TextWatcher() {
@Override
public void onTextChanged(CharSequence s, int start, int before,
int count) {
//控制金額格式
if (s.toString().contains(".")) {
if (s.length() - 1 - s.toString().indexOf(".") > 2) {
s = s.toString().subSequence(0,
s.toString().indexOf(".") + 3);
editText.setText(s);
editText.setSelection(s.length());
}
}
if (s.toString().trim().substring(0).equals(".")) {
s = "0" + s;
editText.setText(s);
editText.setSelection(2);
}
String input = s.toString().trim();
if (!TextUtils.isEmpty(input)) {
float value = Float.valueOf(input);
if (value > max) {
s = String.valueOf(max);
editText.setText(String.valueOf(max));
}
}
if (s.toString().startsWith("0")
&& s.toString().trim().length() > 1) {
if (!s.toString().substring(1, 2).equals(".")) {
editText.setText(s.subSequence(0, 1));
editText.setSelection(1);
return;
}
}
}
@Override
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
}
@Override
public void afterTextChanged(Editable s) {
if (TextUtils.isEmpty(s.toString().trim()))
return;
float value = Float.valueOf(s.toString().trim());
int position = (int) (value / unitValue);
if (value > max) {
position = (int) (max / unitValue);
}
mWheelView.selectIndex(position);//控制游標變化
}
});
}
}