android:background="@null"
getBinding().editText1.setFocusable(true);
getBinding().editText1.setFocusableInTouchMode(true);
getBinding().editText1.requestFocus();
这种情况一般是通过代码直接设置的文本,光标没有移动到最后的问题
// 获取输入的文本内容
String content = getBinding().editText2.getText().toString();
// 获取输入文本字符串的长度
int length = content.length();
// 将光标移到最后
getBinding().editText2.setSelection(length);
android:scrollbars="none"
先来看下布局(示例),注意 ScrollView 中只能包含一个布局
<ScrollView
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<ImageView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:src="@drawable/picture1"/>
<ImageView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:src="@drawable/picture2"/>
LinearLayout>
ScrollView>
然后来看下 EditText 的滑动效果。很明显,EditText 的滑动被 ScrollView劫持了,只执行 ScrollView 的滑动了
getBinding().editText2.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
boolean isLastLineReached = !v.canScrollVertically(1); // 是否滑动到最后一行
boolean isTopLineReached = !v.canScrollVertically(-1); // 是否滑动到首行
if ((isLastLineReached && event.getAction() == MotionEvent.ACTION_DOWN)
|| (isTopLineReached && event.getAction() == MotionEvent.ACTION_UP)) {
v.getParent().requestDisallowInterceptTouchEvent(false); // 放弃事件
} else {
v.getParent().requestDisallowInterceptTouchEvent(true); // 禁止 ScrollView 处理事件
}
return false;
}
});
getBinding().editText2.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void onTextChanged(CharSequence charSequence, int start, int before, int count) {
// 更新 TextView 显示的字符计数
getBinding().tvCount.setText(String.format("输入框内有:%d个字符", charSequence.length()));
}
@Override
public void afterTextChanged(Editable s) {
}
});
// 限制最大输入为10个字符
getBinding().editText2.setFilters(new InputFilter[]{new MaxTextLengthFilter(10)});
public static class MaxTextLengthFilter implements InputFilter {
private final int mMaxLength;
// 构造方法中传入最多能输入的字数
public MaxTextLengthFilter(int max) {
mMaxLength = max;
}
public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) {
int keep = mMaxLength - (dest.length() - (dend - dstart));
if (keep < (end - start)) {
ToastManager.showShort("不能超过" + mMaxLength + "个字符");
}
if (keep <= 0) {
return "";
} else if (keep >= end - start) {
return null;
} else {
return source.subSequence(start, start + keep);
}
}
}