需求:
未输入文字前无效果,输入文字后,后面紧跟一个单位,清除输入内容后,该单位(文字)消失!
效果图:
实现思路:
1、自定义view继承Edittext
2、对Edittext进行输入监听,在文字末尾添加文本
核心代码:
private TextWatcher textWatcher = 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 s) {
if (ceText.trim().isEmpty())
return;
if (s != null) {
removeTextChangedListener(this);//移除输入监听
if (s.toString().trim().equals(ceText)) {
setText("");
} else {
String str = s.toString().replace(ceText, "") + ceText;//去重
setText(str);
}
addTextChangedListener(this);
}
}
};
分析:
主要是在文字输入完成后,进行内容处理,进行文本拼接
设置文本前要记得取消输入监听,不然会一直循环,导致卡死
处理完毕后记得重新注册输入监听。
如何使用:
dependencies {
implementation 'com.github.OneGreenHand:CompanyEdittext:v1.0'
}
属性说明
ce_text:文本
ce_text_color:文本颜色
for example
<com.green.hand.library.CompanyEdittext
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="剩余可提现7500元"
android:inputType="number"
android:paddingTop="10dp"
android:paddingBottom="10dp"
app:ce_text="元"
app:ce_text_color="#CCCCCC" />
Github直达
欢迎Start或提issues!!!