自定义控件-金额输入框

最近项目上用到一个金额输入的功能,基本功能包括可以输入小数,然后小数位数限制为2位。

我用自定义的EditText实现了这个功能


思路:写一个类继承EditText,然后在构造方法中设置OnTextChangeLisener,如果输入的文字包含小数点,且小数位大于2,则在输入完后,删除掉最后一位


代码如下:

/**
 * 金额输入框,限制小数位为2位
 * 
 * @author xianglongzhou
 * 
 */
public class MoneyEditText extends EditText {
	private static final String TAG = "MoneyEditText";
	private boolean textChange;
	
	public MoneyEditText(Context context) {
		this(context, null);
	}

	public MoneyEditText(Context context, AttributeSet attrs) {
		this(context, attrs, 0);
	}

	public MoneyEditText(Context context, AttributeSet attrs, int defStyleAttr) {
		super(context, attrs, defStyleAttr);
		//设置可以输入小数
		setInputType(InputType.TYPE_CLASS_NUMBER | InputType.TYPE_NUMBER_FLAG_DECIMAL);
		setFocusable(true);
		setFocusableInTouchMode(true);
		//监听文字变化
		addTextChangedListener(new TextWatcher() {
			
			@Override
			public void onTextChanged(CharSequence s, int start, int before, int count) {
				
			}
			
			@Override
			public void beforeTextChanged(CharSequence s, int start, int count,
					int after) {
				
			}
			
			@Override
			public void afterTextChanged(Editable s) {
				if(!textChange){
					restrictText();
				}
				textChange = false;
			}
		});
	}



	/**
	 * 将小数限制为2位
	 */
	private void restrictText() {
		String input = getText().toString();
		if(TextUtils.isEmpty(input)){
			return;
		}
		if (input.contains(".")) {
			int pointIndex = input.indexOf(".");
			int totalLenth = input.length();
			int len = (totalLenth-1) - pointIndex;
			if(len > 2){
				input = input.substring(0,totalLenth - 1);
				textChange = true;
				setText(input);
				setSelection(input.length());
			}
		}
		
	}
	
	/**
	 * 获取金额
	 */
	public String getMoneyText(){
		String money = getText().toString();
		//如果最后一位是小数点
		if(money.endsWith(".")){
			return money.substring(0, money.length() - 1);
		}
		return money;
	}
}




猜你喜欢

转载自blog.csdn.net/irxiang/article/details/51277609