最近一个需求,未登录状态点击评论框去登录,登录成功后回来评论框正常使用。
// p层
@Override
public void initEditTextStatus() {
if (UserRepository.getInstance().isSaleIdentity() || !UserRepository.getInstance().userIsLogin()){
mView.setEditTextStatus(false);
} else {
mView.setEditTextStatus(true);
}
}
// p层调此方法
@Override
public void setEditTextStatus(boolean enable) {
// 主要加了这句代码
etCommentContent.setFocusableInTouchMode(enable);
etCommentContent.setFocusable(enable);
etCommentContent.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if (!UserRepository.getInstance().userIsLogin()) {
toLoginActivity();
} else if (UserRepository.getInstance().isSaleIdentity()) {
toastMsg("销售身份无法发表评论");
}
}
});
}
- 一开始进去界面初始化的时候,这个编辑框的Focusable状态是false
- 登录回来去重置这个编辑框的状态,setFocuable(true),无效,打个断点,直接捕获了一个空指针异常
- 编辑框是空的,百思不得其解,界面又没销毁,怎么能是空的呢,后来加个setFocusableInTouchMode()就ok了
- 找下源码,不往深看,简单看一下这三个方法
public void setFocusable(boolean focusable) {
setFocusable(focusable ? FOCUSABLE : NOT_FOCUSABLE);
}
public void setFocusable(@Focusable int focusable) {
if ((focusable & (FOCUSABLE_AUTO | FOCUSABLE)) == 0) {
setFlags(0, FOCUSABLE_IN_TOUCH_MODE);
}
setFlags(focusable, FOCUSABLE_MASK);
}
public void setFocusableInTouchMode(boolean focusableInTouchMode) {
// Focusable in touch mode should always be set before the focusable flag
// otherwise, setting the focusable flag will trigger a focusableViewAvailable()
// which, in touch mode, will not successfully request focus on this view
// because the focusable in touch mode flag is not set
setFlags(focusableInTouchMode ? FOCUSABLE_IN_TOUCH_MODE : 0, FOCUSABLE_IN_TOUCH_MODE);
// Clear FOCUSABLE_AUTO if set.
if (focusableInTouchMode) {
// Clears FOCUSABLE_AUTO if set.
setFlags(FOCUSABLE, FOCUSABLE_MASK);
}
}
重点是这段注释:
- // Focusable in touch mode should always be set before the focusable flag
- // otherwise, setting the focusable flag will trigger a focusableViewAvailable()
- // which, in touch mode, will not successfully request focus on this view
- // because the focusable in touch mode flag is not set
用本人撇脚的英语翻译一下就是:
- 应该始终获取焦点标志前去设置在可触摸模式下聚焦
- 否则,设置ficusable标志将触发focusableViewAvailable()
- 所以在触摸模式下,将不会成功的请求到视图的焦点
- 因为没有设置可触摸模式标志中的可聚焦
所以说在调setFocusable之前得调一下setFocusableInTouchMode
最后
我被这个问题困扰了,而且不知道为啥,他就不管用,而且打断点还空指针
现在是明白了,记录一下,开发中遇到的坑。。。
如果帮到你给个赞~