EditText相关

EditText属性

EditText继承关系:View–>TextView–>EditText

EditText部分属性介绍:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
android:hint="请输入数字!"//设置显示在空间上的提示信息
android:numeric="integer"//设置只能输入整数,如果是小数则是:decimal
android:singleLine="true"//设置单行输入,一旦设置为true,则文字不会自动换行。
android:password="true"//设置只能输入密码
android:textColor = "#ff8c00"//字体颜色
android:textStyle="bold"//字体,bold, italic, bolditalic
android:textSize="20dip"//大小
android:capitalize = "characters"//以大写字母写
android:textAlign="center"//EditText没有这个属性,但TextView有,居中
android:textColorHighlight="#cccccc"//被选中文字的底色,默认为蓝色
android:textColorHint="#ffff00"//设置提示信息文字的颜色,默认为灰色android:textScaleX="1.5"//控制字与字之间的间距
android:typeface="monospace"//字型,normal, sans, serif, monospace
android:background="@null"//背景,这里没有,指透明
android:layout_weight="1"//权重,控制控件之间的地位,在控制控件显示的大小时蛮有用的。
android:textAppearance="?android:attr/textAppearanceLargeInverse"//文字外观
android:layout_gravity="center_vertical"//设置控件显示的位置:默认top,这里居中显示,还有bottom

android:gravity="top" //多行中指针在第一行第一位置
et.setSelection(et.length());//调整光标到最后一行
android:autoText //自动拼写帮助
android:capitalize //首字母大写
android:digits //自己设置规则android:digits="0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
Android:singleLine//是否单行或者多行,回车是离开文本框还是文本框增加新行
android:numeric //只接受数字
android:phoneNumber //输入电话号码
android:editable //是否可编辑
android:autoLink=”all” //设置文本超链接样式当点击网址时,跳向该网址
android:textAppearance="?android:attr/textAppearanceLargeInverse"//文字外观,这里引用的是系统自带的一个外观,?表示系统是否有这种外观,否则使用默认的外观。不知道这样理解对不对?


android:fastScrollEnabled="true" //滑块
android:choiceMode="multipleChoice" //设置选择模式,他包括几个选择 CHOICE_MODE_MULTIPLE(多选), CHOICE_MODE_NONE(默认),CHOICE_MODE_SINGLE(单选)

代码中限制输入字数

1
edt.setFilters(new InputFilter[]{new InputFilter.LengthFilter(length)});

限制Edt内容

限制Edt输入内容的类型

自定义TextWatcher类

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
public class LimitInputTextWatcher implements TextWatcher {
private EditText et = null;
/**
* 筛选条件
*/
private String regex;
/**
* 默认的筛选条件(正则:只能输入中文)
*/
private String DEFAULT_REGEX = "[^\u4E00-\u9FA5]";

public LimitInputTextWatcher(EditText et) {
this.et = et;
this.regex = DEFAULT_REGEX;
}

public LimitInputTextWatcher(EditText et, String regex) {
this.et = et;
this.regex = regex;
}

@Override
public void beforeTextChanged(CharSequence charSequence, int start, int count, int after) {

}

@Override
public void onTextChanged(CharSequence charSequence, int start, int before, int count) {

}

@Override
public void afterTextChanged(Editable editable) {
String str = editable.toString();
String inputStr = clearLimitStr(regex, str);
et.removeTextChangedListener(this);
//et.setText方法可能会引起键盘变化,所以用editable.replace来显示内容
editable.replace(0, editable.length(), inputStr.trim());
et.addTextChangedListener(this);
}

/**
* 清除不符合条件的内容
* @param regex
* @param str
* @return
*/
private String clearLimitStr(String regex, String str){
return str.replaceAll(regex, "");
}
}

调用

1
2
3
4
// 只允许字母、汉字
String regEx = "[^a-zA-Z\u4E00-\u9FA5]";//正则表达式
//String regEx = "[^a-zA-Z0-9\u4E00-\u9FA5]";//只允许字母、数字、汉字
et.addTextChangedListener(new LimitInputTextWatcher(et, regEx));

限制Edt只能输入整数或者最多两位小数,且整数不能以0开头

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
edt.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) {

}

@Override
public void afterTextChanged(Editable editable) {
try {
if (!StringUtils.isEmpty(editable.toString().trim())) {
edt.removeTextChangedListener(this);
String matchRet = match(editable.toString().trim());
//et.setText方法可能会引起键盘变化,所以用editable.replace来显示内容
editable.replace(0, editable.length(), matchRet);
edt.addTextChangedListener(this);
}
} catch (Exception e) {
e.printStackTrace();
}
}
});
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
/**
* 返回整数、两位小数、0
*/
private String match(String text){
//增加判空,防止删除最后一位数字后依旧会返回“0”
if (TextUtils.isEmpty(text)){
return text;
}
//匹配整数、两位小数、0
Pattern pattern = Pattern.compile("^[1-9]\\d*(\\.\\d{0,2})?|0\\.\\d{0,2}|0$");
Matcher matcher = pattern.matcher(text);
if(matcher.find()){
return matcher.group(0);
}
return "0";
}

限制首位不能是空格

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
edt.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) {

}

@Override
public void afterTextChanged(Editable editable) {
try {
if (editable.toString().length() == 1 && TextUtils.equals(editable.toString(), " ")) {
mBinding.searchBar.removeTextChangedListener(this);
//et.setText方法可能会引起键盘变化,所以用editable.replace来显示内容
editable.replace(0, editable.length(), "");
mBinding.searchBar.addTextChangedListener(this);
}
} catch (Exception e) {
e.printStackTrace();
}
}
});

限制Edt不能输入表情符号

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
InputFilter inputFilter = new InputFilter() {
Pattern emoji = Pattern.compile("[\ud83c\udc00-\ud83c\udfff]|[\ud83d\udc00-\ud83d\udfff]|[\u2600-\u27ff]",Pattern.UNICODE_CASE | Pattern.CASE_INSENSITIVE);
//Pattern pattern = Pattern.compile("[^a-zA-Z0-9\\u4E00-\\u9FA5_]");//汉字,英文,数字

@Override
public CharSequence filter(CharSequence charSequence, int i, int i1, Spanned spanned, int i2, int i3) {
Matcher matcher = emoji.matcher(charSequence);
if (matcher.find()) {
ToastUtil.showToast(ApplyShowTaskActivity.this, "不支持输入表情");
return "";
}
return null;
}
};

//第一参数屏蔽表情;第二个参数限制输入的字数(20个字)
edtTest.setFilters(new InputFilter[]{inputFilter, new InputFilter.LengthFilter(20)});

上面限制的表情会有少部分没法限制

限制输入类型,且首位是下划线或字母开头

微信号规则:微信号必须以字母或者下划线开头,可以使用6-20位数字、字母、下划线、减号或它们的组合

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
String digits = "_-0123456789qwertyuiopasdfghjklzxcvbnmQWERTYUIOPASDFGHJKLZXCVBNM";
mBinding.etChangeUserName.setDigits(digits);
mBinding.etChangeUserName.addBETextChangedListener(new KButtonEditText.kBetCenterEditTextWatcher() {
@Override
public void beforeKBetCenterEditTextChanged(CharSequence s, int start, int count, int after) {
}

@Override
public void onKBetCenterEditTextChanged(CharSequence s, int start, int before, int count) {
}

@Override
public void afterKBetCenterEditTextChanged(Editable editable) {
//限制输入内容的类型
String str = editable.toString();
if (str.length() > 0) {
//限制首位是下划线或字母
if (!isStartMatcher(str)) {
ToastUtils.showCenter(getResources().getString(R.string.wx_no_limit));
if (str.length() == 1) {
mBinding.etChangeUserName.setText("");
}
mBinding.btnNextChangePass.setEnabled(false);
return;
}
}
mBinding.etChangeUserName.removeBETextChangedListener();
//et.setText方法可能会引起键盘变化,所以用editable.replace来显示内容
editable.replace(0, editable.length(), str.trim());
mBinding.etChangeUserName.addBETextChangedListener(this);

//do something...
}

/**
* 首位是下划线或字母
*/
public boolean isStartMatcher(String string) {
String digits = "_qwertyuiopasdfghjklzxcvbnmQWERTYUIOPASDFGHJKLZXCVBNM";
for (int i = 0; i < digits.length(); i++) {
char c = digits.charAt(i);
if (string.startsWith(String.valueOf(c))) {
return true;
}
}
return false;
}
});

过滤Edt内容

1
2
3
4
public static void setProhibitEmoji(EditText et) {
InputFilter[] filters = { getInputFilterProhibitEmoji() };
et.setFilters(filters);
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
public static InputFilter getInputFilterProhibitEmoji() {
InputFilter filter = new InputFilter() {
@Override
public CharSequence filter(CharSequence source, int start, int end,
Spanned dest, int dstart, int dend) {
StringBuffer buffer = new StringBuffer();
for (int i = start; i < end; i++) {
char codePoint = source.charAt(i);
if (!getIsEmoji(codePoint)) {
buffer.append(codePoint);
} else {
i++;
continue;
}
}
if (source instanceof Spanned) {
SpannableString sp = new SpannableString(buffer);
TextUtils.copySpansFrom((Spanned) source, start, end, null,
sp, 0);
return sp;
} else {
return buffer;
}
}
};
return filter;
}
1
2
3
4
5
6
7
8
9
public static boolean getIsEmoji(char codePoint) {
if ((codePoint == 0x0) || (codePoint == 0x9) || (codePoint == 0xA)
|| (codePoint == 0xD)
|| ((codePoint >= 0x20) && (codePoint <= 0xD7FF))
|| ((codePoint >= 0xE000) && (codePoint <= 0xFFFD))
|| ((codePoint >= 0x10000) && (codePoint <= 0x10FFFF)))
return false;
return true;
}

上面这种限制的表情更不全(比上面《限制Edt不能输入表情符号》更不全)

保证点击editText时光标总在最后

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
package com.landi.sqsm.cashier.widget;

import android.annotation.SuppressLint;
import android.content.Context;
import android.util.AttributeSet;
import android.util.Log;
import android.widget.EditText;

@SuppressLint("AppCompatCustomView")
public class LastInputEditText extends EditText {
static String TAG = "LastInputEditText";
public LastInputEditText(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}

public LastInputEditText(Context context, AttributeSet attrs) {
super(context, attrs);
}

public LastInputEditText(Context context) {
super(context);
}

@Override
public void setSelection(int start, int stop) {
super.setSelection(start, stop);
Log.i(TAG,"执行了setSelection1: " + "start:" + start + " stop:" +stop);
}

@Override
public void setSelection(int index) {
super.setSelection(index);
Log.i(TAG,"执行了setSelection2");
}

@Override
public void onSelectionChanged(int selStart, int selEnd) {
//super.onSelectionChanged(selStart, selEnd);
Log.i(TAG,"执行了onSelectionChanged" + "selStart:" + selStart + "selEnd:" + selEnd);
//保证光标始终在最后面
if(selStart==selEnd){//防止不能多选
setSelection(getText().length());
}
//setSelection(getText().length());
}
}

光标显示在最后一位且弹出键盘

1
2
3
4
5
6
7
8
9
//使用控件.post确保控件已经渲染完毕
edt.post(()->{
edt.setFocusable(true);
edt.setFocusableInTouchMode(true);
edt.requestFocus();
//这句是关键
AttachmentRenameActivity.this.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);
edt.setSelection(edt.getText().length());
});

代码中设置了setSoftInputMode,AndroidManifest中可以不用设置 android:windowSoftInputMode=”stateVisible”

光标透明

在drawable下新建edittext_cursor.xml

1
2
3
4
5
<?xml version="1.0" encoding="utf-8"?>  
<shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="rectangle">
<size android:width="1dp" />
<solid android:color="#00000000" />
</shape>

在xml的<EditText>上使用

1
android:textCursorDrawable="@drawable/edittext_cursor"

验证码框效果

实现:4个TextView,上面覆盖一个EditText。EditText接收输入、黏贴等,再把内容截取设置到对应的Tv上。另外,要让光标透明(因为EditText上的光标位置并没有对应上tv)

注意:EditText的cursorVisible得是true,否则长按黏贴功能使用不了

完整代码

自定义控件

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
public class VerificationCodeEditText extends KDataBindingCustomView<VerificationCodeEditTextBinding> {

private final int mHightLightColor;
private final int mDefaultColor;
private OnTextChangeListener mListener;

public VerificationCodeEditText(@NonNull Context context) {
this(context, null);
}

public VerificationCodeEditText(@NonNull Context context, @Nullable AttributeSet attrs) {
this(context, attrs, 0);
}

public VerificationCodeEditText(@NonNull Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
mHightLightColor = ResourcesCompat.getColor(getResources(), R.color.colorAppTheme, null);
mDefaultColor = ResourcesCompat.getColor(getResources(), R.color.color999999, null);
initViews();
}

@Override
protected int setLayoutRes() {
return R.layout.layout_verification_code_edit_text;
}

private void initViews() {
//验证码输入
mBinding.etVerificationCodeEditText.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
}

@Override
public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
}

@Override
public void afterTextChanged(Editable editable) {
String trim = mBinding.etVerificationCodeEditText.getText().toString().trim();
if (AppStringUtils.isEmpty(trim)) {
mBinding.tvVerificationCodeEditText1.setText("");
mBinding.tvVerificationCodeEditText2.setText("");
mBinding.tvVerificationCodeEditText3.setText("");
mBinding.tvVerificationCodeEditText4.setText("");

mBinding.div1VerificationCodeEditText.setBackgroundColor(mHightLightColor);
mBinding.div2VerificationCodeEditText.setBackgroundColor(mDefaultColor);
mBinding.div3VerificationCodeEditText.setBackgroundColor(mDefaultColor);
mBinding.div4VerificationCodeEditText.setBackgroundColor(mDefaultColor);
} else if (trim.length() == 1) {
mBinding.tvVerificationCodeEditText1.setText(trim);
mBinding.tvVerificationCodeEditText2.setText("");
mBinding.tvVerificationCodeEditText3.setText("");
mBinding.tvVerificationCodeEditText4.setText("");

mBinding.div1VerificationCodeEditText.setBackgroundColor(mDefaultColor);
mBinding.div2VerificationCodeEditText.setBackgroundColor(mHightLightColor);
mBinding.div3VerificationCodeEditText.setBackgroundColor(mDefaultColor);
mBinding.div4VerificationCodeEditText.setBackgroundColor(mDefaultColor);
} else if (trim.length() == 2) {
mBinding.tvVerificationCodeEditText1.setText(trim.substring(0, 1));
mBinding.tvVerificationCodeEditText2.setText(trim.substring(1, 2));
mBinding.tvVerificationCodeEditText3.setText("");
mBinding.tvVerificationCodeEditText4.setText("");

mBinding.div1VerificationCodeEditText.setBackgroundColor(mDefaultColor);
mBinding.div2VerificationCodeEditText.setBackgroundColor(mDefaultColor);
mBinding.div3VerificationCodeEditText.setBackgroundColor(mHightLightColor);
mBinding.div4VerificationCodeEditText.setBackgroundColor(mDefaultColor);
} else if (trim.length() == 3) {
mBinding.tvVerificationCodeEditText1.setText(trim.substring(0, 1));
mBinding.tvVerificationCodeEditText2.setText(trim.substring(1, 2));
mBinding.tvVerificationCodeEditText3.setText(trim.substring(2, 3));
mBinding.tvVerificationCodeEditText4.setText("");

mBinding.div1VerificationCodeEditText.setBackgroundColor(mDefaultColor);
mBinding.div2VerificationCodeEditText.setBackgroundColor(mDefaultColor);
mBinding.div3VerificationCodeEditText.setBackgroundColor(mDefaultColor);
mBinding.div4VerificationCodeEditText.setBackgroundColor(mHightLightColor);
} else if (trim.length() == 4) {
mBinding.tvVerificationCodeEditText1.setText(trim.substring(0, 1));
mBinding.tvVerificationCodeEditText2.setText(trim.substring(1, 2));
mBinding.tvVerificationCodeEditText3.setText(trim.substring(2, 3));
mBinding.tvVerificationCodeEditText4.setText(trim.substring(3, 4));
}
if (mListener != null) {
mListener.afterTextChanged(editable.toString());
}
}
});
}

public void clearText() {
mBinding.etVerificationCodeEditText.setText("");
}

public void setTextChangeListener(OnTextChangeListener listener) {
mListener = listener;
}

public interface OnTextChangeListener {
void afterTextChanged(String s);
}
public String getText() {
return mBinding.etVerificationCodeEditText.getText().toString().trim();
}

public EditText getInputEt(){
return mBinding.etVerificationCodeEditText;
}
}

其中的KDataBindingCustomView

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
/**
* 说明:自定义DataBinding的控件
*/
public abstract class KDataBindingCustomView<VD extends ViewDataBinding> extends FrameLayout {

protected VD mBinding;

public KDataBindingCustomView(@NonNull Context context) {
this(context, null);
}

public KDataBindingCustomView(@NonNull Context context, @Nullable AttributeSet attrs) {
this(context, attrs, 0);
}

public KDataBindingCustomView(@NonNull Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
mBinding = DataBindingUtil.inflate(LayoutInflater.from(context), setLayoutRes(), this, true);
}

protected abstract int setLayoutRes();
}

布局文件layout_verification_code_edit_text.xml

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
<?xml version="1.0" encoding="utf-8"?>
<layout xmlns:android="http://schemas.android.com/apk/res/android">

<data class="VerificationCodeEditTextBinding">

</data>

<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">

<LinearLayout
android:id="@+id/ll_verification_code_edit_text"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">

<LinearLayout
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginEnd="@dimen/viewSize8"
android:layout_weight="1"
android:orientation="vertical">

<TextView
android:id="@+id/tv_verification_code_edit_text_1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="@null"
android:gravity="center"
android:textColor="@color/colorAppMainText"
android:textSize="@dimen/viewSize40" />

<View
android:id="@+id/div1_verification_code_edit_text"
android:layout_width="match_parent"
android:layout_height="@dimen/viewSize1"
android:background="@color/colorAppTheme" />
</LinearLayout>

<LinearLayout
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginEnd="@dimen/viewSize8"
android:layout_weight="1"
android:orientation="vertical">

<TextView
android:id="@+id/tv_verification_code_edit_text_2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="@null"
android:gravity="center"
android:textColor="@color/colorAppMainText"
android:textSize="@dimen/viewSize40" />

<View
android:id="@+id/div2_verification_code_edit_text"
android:layout_width="match_parent"
android:layout_height="@dimen/viewSize1"
android:background="@color/color999999" />
</LinearLayout>

<LinearLayout
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginEnd="@dimen/viewSize8"
android:layout_weight="1"
android:orientation="vertical">

<TextView
android:id="@+id/tv_verification_code_edit_text_3"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="@null"
android:gravity="center"
android:textColor="@color/colorAppMainText"
android:textSize="@dimen/viewSize40" />

<View
android:id="@+id/div3_verification_code_edit_text"
android:layout_width="match_parent"
android:layout_height="@dimen/viewSize1"
android:background="@color/color999999" />
</LinearLayout>

<LinearLayout
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginEnd="@dimen/viewSize8"
android:layout_weight="1"
android:orientation="vertical">

<TextView
android:id="@+id/tv_verification_code_edit_text_4"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="@null"
android:gravity="center"
android:textColor="@color/colorAppMainText"
android:textSize="@dimen/viewSize40" />

<View
android:id="@+id/div4_verification_code_edit_text"
android:layout_width="match_parent"
android:layout_height="@dimen/viewSize1"
android:background="@color/color999999" />
</LinearLayout>
</LinearLayout>

<EditText
android:id="@+id/et_verification_code_edit_text"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignTop="@+id/ll_verification_code_edit_text"
android:layout_alignBottom="@+id/ll_verification_code_edit_text"
android:background="@color/colorTranslucent"
android:cursorVisible="true"
android:inputType="number"
android:maxLength="4"
android:textCursorDrawable="@drawable/edittext_cursor"
android:textColor="@color/colorTranslucent" />
</RelativeLayout>

</layout>

使用

1
2
3
4
5
6
7
8
<xxx.widget.verifycode.VerificationCodeEditText
android:id="@+id/et_auth_code_v1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginHorizontal="@dimen/viewSize24"
android:layout_marginTop="@dimen/viewSize16"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@id/tv_tip_auth_code_v1" />

问题:无法一进入页面就弹出键盘

解决:给对应editText设置个延迟的展示键盘(用延迟的获取焦点可能还无法唤起键盘)

1
mBinding.etAuthCodeV1.getInputEt().postDelayed(() -> com.blankj.utilcode.util.KeyboardUtils.showSoftInput(mBinding.etAuthCodeV1.getInputEt()), 200);

Demo

可清空的edittext

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
import android.content.Context;
import android.graphics.Rect;
import android.graphics.drawable.Drawable;
import android.util.AttributeSet;
import android.view.MotionEvent;

import androidx.appcompat.widget.AppCompatEditText;

/**
* desc : 可清空的edittext
*/
public class ClearableEditText extends AppCompatEditText {
private static final int DRAWABLE_LEFT = 0;
private static final int DRAWABLE_TOP = 1;
private static final int DRAWABLE_RIGHT = 2;
private static final int DRAWABLE_BOTTOM = 3;
private Drawable mClearDrawable;

public ClearableEditText(Context context) {
super(context);
init();
}

public ClearableEditText(Context context, AttributeSet attrs) {
super(context, attrs);
init();
}

public ClearableEditText(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
init();
}

private void init() {
mClearDrawable = getResources().getDrawable(R.drawable.icon_x_1);
}

@Override
protected void onTextChanged(CharSequence text, int start, int lengthBefore, int lengthAfter) {
super.onTextChanged(text, start, lengthBefore, lengthAfter);
setClearIconVisible(hasFocus() && text.length() > 0);
}

@Override
protected void onFocusChanged(boolean focused, int direction, Rect previouslyFocusedRect) {
super.onFocusChanged(focused, direction, previouslyFocusedRect);
setClearIconVisible(focused && length() > 0);
}

@Override
public boolean onTouchEvent(MotionEvent event) {
switch (event.getAction()) {
case MotionEvent.ACTION_UP:
Drawable drawable = getCompoundDrawables()[DRAWABLE_RIGHT];
if (drawable != null && event.getX() <= (getWidth() - getPaddingRight())
&& event.getX() >= (getWidth() - getPaddingRight() - drawable.getBounds().width())) {
setText("");
}
break;
}
return super.onTouchEvent(event);
}

private void setClearIconVisible(boolean visible) {
setCompoundDrawablesWithIntrinsicBounds(getCompoundDrawables()[DRAWABLE_LEFT], getCompoundDrawables()[DRAWABLE_TOP],
visible ? mClearDrawable : null, getCompoundDrawables()[DRAWABLE_BOTTOM]);
}
}

问题

EditText全选效果无效

现象:点击之后,先出现全选,然后会失去全选的效果

解决:思路是借助外部新建的一个EditText控件,在onTouch时先把焦点给其他的EditText,然后再设置全选

1
2
3
4
5
6
7
8
if(motionEvent.getAction() == MotionEvent.ACTION_UP){
fragmentScanPlatepayNo.requestFocus();//这个时另外一个edittext获取焦点
if(StringUtil.isNotEmpty(fragmentScanPlatepayAcctMoney.getText().toString())){
fragmentScanPlatepayAcctMoney.selectAll();
fragmentScanPlatepayAcctMoney.setSelectAllOnFocus(true);
keyBoardNumLayout.setSelect(true);
}
}

xml布局中:

1
2
android:focusable="true"
android:selectAllOnFocus="true"

全部代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
fragmentScanPlatepayAcctMoney.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View view, MotionEvent motionEvent) {
// 此处为得到焦点时的处理内容
fragmentScanPlatepayNo.requestFocus();//这里的作用是每次点击的时候 还可以全选
if (fragmentScanPlatepayAcctMoney != null) {
keyBoardNumLayout.setVisibility(View.VISIBLE);
}
if(motionEvent.getAction() == MotionEvent.ACTION_UP){
if (StringUtil.isNotEmpty(fragmentScanPlatepayAcctMoney.getText().toString())) {
fragmentScanPlatepayAcctMoney.selectAll();
fragmentScanPlatepayAcctMoney.setSelectAllOnFocus(true);
keyBoardNumLayout.setSelect(true);
}
}
return false;
}
});
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
<EditText
android:id="@+id/fragment_scan_platepay_acct_money"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_gravity="center"
android:background="@null"
android:cursorVisible="true"
android:digits="0123456789."
android:focusable="true"
android:selectAllOnFocus="true"
android:gravity="center|center_vertical"
android:hint="请输入金额"
android:imeOptions="actionNext"
android:inputType="none"
android:maxLength="20"
android:paddingStart="10dp"
android:paddingEnd="10dp"
android:privateImeOptions="inputmode=number|disable=chinese,eng_upper,eng_lower,interpunction,space"
android:singleLine="true"
android:textColor="@color/black"
android:textCursorDrawable="@drawable/cursor_color"
android:textSize="18sp"
android:textStyle="bold" />

edittext和Scrollview滑动条冲突问题

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
//解决edittext和Scrollview滑动条冲突问题
edt.setOnTouchListener(new OnTouchListener() {

@Override
public boolean onTouch(View v, MotionEvent event) {
v.getParent().requestDisallowInterceptTouchEvent(true);
switch (event.getAction() & MotionEvent.ACTION_MASK) {
case MotionEvent.ACTION_UP:
v.getParent().requestDisallowInterceptTouchEvent(false);
break;
default:
break;
}
return false;
}
});

EditText不自动换行

添加属性android:inputType="textMultiLine"

EditText添加addTextChangedListener后手写时无法正常使用