700字范文,内容丰富有趣,生活中的好帮手!
700字范文 > android仿微信充值布局 仿微信充值金额输入框-自定义EditText

android仿微信充值布局 仿微信充值金额输入框-自定义EditText

时间:2020-02-04 02:21:10

相关推荐

android仿微信充值布局 仿微信充值金额输入框-自定义EditText

1. 概述

在开发过程中,有时候我们需要在输入框中输入金额,并且输入金额有一定的规则限制:

1>:只能是数字;

2>:第一位只能是数字,不能是小数点,如果第一位是小数点,就默认在小数点前加0,且保留2位小数;

2. 效果图如下

图片.png

3. 代码如下

1>:自定义可以输入金额的输入框MoneyEditText:

/**

* Created by yinhaiyang on /4/21.

* 自定义可输入金额的EditText(仿微信输入框效果)

*/

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());

}

}

if (input.toString().trim().substring(0).equals(".")) {

input = "0" + input;

setText(input);

setSelection(2);

}

}

/**

* 获取金额

*/

public String getMoneyText() {

String money = getText().toString();

//如果最后一位是小数点

if (money.endsWith(".")) {

return money.substring(0, money.length() - 1);

}

return money;

}

}

2>:在布局文件中直接引用:

android:inputType="number"

android:textCursorDrawable="@null"

android:maxLength="12"

android:id="@+id/et_at_trad_money"

android:hint=""

android:background="@null"

android:layout_gravity="center_vertical"

android:textColor="@color/n_0_0_0"

android:textSize="24sp"

android:layout_width="match_parent"

android:layout_height="wrap_content" />

4. 需要注意的是:

在布局文件中设置 maxLength=12,是不能限制输入字符的最大长度,需要在代码中设置:

private MoneyEditText etTradMoney;

//即限定最大输入字符数为20

etTradMoney.setFilters(new InputFilter[]{new InputFilter.LengthFilter(12)});

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。