EditText
文本输入框, Android
里面超级常用的控件,不管你是要进行注册登录还是表单填写,肯定都需要和它打交道,写下目前已知的各种问题。
保存状态恢复异常
这个都知道,通常我们不需要额外注意和处理 EditText
的临时保存以及恢复,因为它早就处理好这一系列的逻辑。但是,请注意,这里有一个但是。EditText 临时保存相关状态是依赖于View 本身 id 作为 key 值,如果你是复用布局,或者存在相同 id ,那么,这个值就是会被覆盖的。
protected void dispatchSaveInstanceState(SparseArray<Parcelable> container) {
if (mID != NO_ID && (mViewFlags & SAVE_DISABLED_MASK) == 0) {
mPrivateFlags &= ~PFLAG_SAVE_STATE_CALLED;
Parcelable state = onSaveInstanceState();
if ((mPrivateFlags & PFLAG_SAVE_STATE_CALLED) == 0) {
throw new IllegalStateException(
"Derived class did not call super.onSaveInstanceState()");
}
if (state != null) {
// Log.i("View", "Freezing #" + Integer.toHexString(mID)
// + ": " + state);
container.put(mID, state);
}
}
}
protected void dispatchRestoreInstanceState(SparseArray<Parcelable> container) {
if (mID != NO_ID) {
Parcelable state = container.get(mID);
if (state != null) {
// Log.i("View", "Restoreing #" + Integer.toHexString(mID)
// + ": " + state);
mPrivateFlags &= ~PFLAG_SAVE_STATE_CALLED;
onRestoreInstanceState(state);
if ((mPrivateFlags & PFLAG_SAVE_STATE_CALLED) == 0) {
throw new IllegalStateException(
"Derived class did not call super.onRestoreInstanceState()");
}
}
}
}
这个是 View
中定义的保存和恢复两个方法,可以看到,没有设置 id 的话,那么就没后续逻辑,在有 id 的情况下,id 就作为 SparseArray
的 key 。所以,再强调下上面提到的:EditText 临时保存相关状态是依赖于View 本身 id 作为 key 值,如果你是复用布局,或者存在相同 id ,那么,这个值就是会被覆盖的。
那这个问题怎么解决好一些呢?先分析下出现这种情况的场景吧。
第一种是复用布局的场景,在 ListView
或者 RecyclerView
中。对应的 EditText
肯定只有一个 id ,这种情况我建议是缓存list相关数据,在恢复时,重新设置相关数据,忽略 EditText
自己的保存和恢复。
第二种是自己定义了一个通用布局父控件,在这个父控件中填充了一个通用布局。对于这种情况,我们不能忽略 EditText
自己的保存和恢复,而是应该改造一下上面讲到的两个方法。具体操作大概就是这样:
private fun initKey(): Any? {
(parent as? View)?.run {
return "${javaClass.simpleName}$$id"
}
return null
}
override fun dispatchSaveInstanceState(container: SparseArray<Parcelable>) {
try {
val key = initKey()
if (key != null && isSaveEnabled) {
val state = onSaveInstanceState()
if (state != null) {
container.put(key.hashCode(), state)
}
}
} catch (e: Exception) {
super.dispatchSaveInstanceState(container)
e.printStackTrace()
}
}
override fun dispatchRestoreInstanceState(container: SparseArray<Parcelable>) {
try {
val key = initKey()
if (key != null) {
val state = container.get(key.hashCode())
if (state != null) {
onRestoreInstanceState(state)
}
}
} catch (e: Exception) {
super.dispatchRestoreInstanceState(container)
e.printStackTrace()
}
}
因为这种情况,父控件总会有一个独立 id ,那么我们就可以通过这个 id 来构造保存时的 key ,接着在恢复时通过对应 key 再去读取相应的 value 。当然你可以再结合第一中情况,加入一个是否缓存的 flag,在列表复用的情况下,直接禁止 EditText
相关数据保存和恢复,也算是一种优化。
imeOptions 总是返回 IME_ACTION_UNSPECIFIED
产品在不断优化之后,提出更加人性化,键盘控制什么的肯定少不了,但是,你应该会碰到过指定 ActionDone
等 action 后却没效果的情况。如果没有,那也看看吧,这里是有一个坑的。对于我已知触发条件是同时指定了这两个属性:
android:digits="@string/code_input_type"
android:inputType="text"
dialogVerifyInput.setOnEditorActionListener { _, actionId, _ ->
if (actionId == EditorInfo.IME_ACTION_DONE) {
dialogVerifyConfirm.performClick()
}
true
}
接着这里 listener 返回的 actionId 就是 IME_ACTION_UNSPECIFIED
,如果上面那两个属性必须指定,其实不用太纠结,直接把 IME_ACTION_UNSPECIFIED
也放到判断条件中,如果能避免,那就避免这么写。
gravity 为 right 时 光标变细
这个问题原因也不太明白,因为有的手机是是 OK 的,有的手机上是有问题的。(似乎不是因为 7.0 版本才有问题,我在 7.0 模拟器上面没有出现对应问题)。网上其实也有相关解决方案,最直接的就是手动追加空格,让光标永远都在倒数第二的位置。
输入模式弹出软键盘遮挡问题
说到 EditText
另一个老大难的问题就是软键盘弹出遮挡的问题。解决方法也很成熟。简单来说就是给 DecorView
添加一个 OnGlobalLayoutListener
,接着通过 DecorView
getWindowVisibleDisplayFrame(rect)
方法拿到可见区域的底部,再和自身的高度做一个对比。
View decorView = activity.getWindow().getDecorView();
decorView.getViewTreeObserver().addOnGlobalLayoutListener(() -> {
Rect rect = new Rect();
decorView.getWindowVisibleDisplayFrame(rect);
int rootHeight = decorView.getRootView().getHeight();
int mainInvisibleHeight = rootHeight - rect.bottom;
if (mainInvisibleHeight > rootHeight / 4) {
int[] location = new int[2];
int srollHeight = 0;
if (scroll != null) {
scroll.getLocationInWindow(location);
srollHeight = location[1] + scroll.getHeight() + dy - rect.bottom;
}
if (srollHeight > 0) {
decorView.scrollTo(0, srollHeight);
}
if (listener != null) {
listener.keybordState(true);
}
} else {
if (scroll != null) {
decorView.scrollTo(0, 0);
}
if (listener != null) {
listener.keybordState(false);
}
}
});
这里有个问题,如果你直接控制滚动的 View
是 DecorView
,状态栏肯定糊掉,在某些带有底部虚拟按键手机上会出现虚拟按键背景色也跟着滚动。所以,这里滚动的 View
应该是自己传入的一个顶级父布局 rootView
,这样滚动的视觉范围就可控制。
public void addKeyboardListener(@NonNull Activity activity, @NonNull View rootView,
@Nullable View targetView, int extraSpace) {
try {
View decorView = activity.getWindow().getDecorView();
decorView.getViewTreeObserver().addOnGlobalLayoutListener(() -> {
Rect rect = new Rect();
decorView.getWindowVisibleDisplayFrame(rect);
int rootHeight = decorView.getRootView().getHeight();
int mainInvisibleHeight = rootHeight - rect.bottom;
if (mainInvisibleHeight > rootHeight / 4) {
int[] location = new int[2];
int scrollHeight = 0;
if (targetView != null) {
targetView.getLocationInWindow(location);
scrollHeight = location[1] + targetView.getHeight() + extraSpace - rect.bottom;
}
if (scrollHeight > 0) {
rootView.scrollTo(0, scrollHeight);
}
} else {
rootView.scrollTo(0, 0);
}
});
} catch (Exception e) {
e.printStackTrace();
}
}
另外记得取消相关事件监听。
setSelection() throw IndexOutOfBoundsException
这个异常产生原因是你设置过 maxLength
, 然后 setSelection()
方法设置的 index 超出了这个 maxLength
。简单点儿 catch 一下异常就好。
网友评论