安卓更改EditText下划线的颜色样式、动态获取输入的字数、设置焦点和软键盘
程序员文章站
2022-04-21 17:50:04
...
在styles.xml文件中声明自定义样式
<style name="MyEditText" parent="Theme.AppCompat.Light">
<item name="colorControlNormal">@color/indigo</item>
<item name="colorControlActivated">@color/pink</item>
</style>
通过android:theme属性将此样式应用于您的EditText
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Hint text"
android:theme="@style/MyEditText"/>
et_comment.addTextChangedListener(mTextWatcher);
et_comment.setFocusable(true);
et_comment.requestFocus();
动态获取输入的字数:
TextWatcher mTextWatcher = new TextWatcher() {
private CharSequence temp;
private int editStart;
private int editEnd;
@Override
public void beforeTextChanged(CharSequence s, int arg1, int arg2,
int arg3) {
temp = s;
}
@Override
public void onTextChanged(CharSequence s, int arg1, int arg2,
int arg3) {
if (s.length() <= 200) {
word_remain.setText((200 - s.length()) + "/200");
}
}
@Override
public void afterTextChanged(Editable s) {
editStart = et_comment.getSelectionStart();
editEnd = et_comment.getSelectionEnd();
if (temp.length() > 200) {
ToastUtil.showToastShort("你输入的字数已经超过了限制!");
s.delete(editStart - 1, editEnd);
int tempSelection = editStart;
et_comment.setText(s);
et_comment.setSelection(tempSelection);
}
}
};
设置焦点和软键盘:
/**
* EditText获取焦点并显示软键盘
*/
public static void showSoftInputFromWindow(Activity activity, EditText editText) {
editText.setFocusable(true);
editText.setFocusableInTouchMode(true);
editText.requestFocus();
activity.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);
}
上一篇: 崩溃bug日志总结2
下一篇: JAVA异常——异常处理