Skip to content

Commit 3f379f3

Browse files
committed
fix findFocus NPE bug
1 parent a4add02 commit 3f379f3

File tree

1 file changed

+29
-20
lines changed

1 file changed

+29
-20
lines changed

anylayer/src/main/java/per/goweii/anylayer/ViewManager.java

Lines changed: 29 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -150,15 +150,21 @@ private void findFocusViewAndBindKeyListener() {
150150
Utils.onViewLayout(mChild, new Runnable() {
151151
@Override
152152
public void run() {
153-
currentKeyView = mChild.findFocus();
154153
if (currentKeyView != null) {
155-
currentKeyView.setOnKeyListener(mLayerKeyListener);
156-
return;
154+
currentKeyView.setOnKeyListener(null);
155+
currentKeyView = null;
157156
}
158-
mChild.requestFocus();
159-
currentKeyView = mChild.findFocus();
160-
if (currentKeyView != null) {
161-
currentKeyView.setOnKeyListener(mLayerKeyListener);
157+
if (isAttached()) {
158+
currentKeyView = mChild.findFocus();
159+
if (currentKeyView != null) {
160+
currentKeyView.setOnKeyListener(mLayerKeyListener);
161+
return;
162+
}
163+
mChild.requestFocus();
164+
currentKeyView = mChild.findFocus();
165+
if (currentKeyView != null) {
166+
currentKeyView.setOnKeyListener(mLayerKeyListener);
167+
}
162168
}
163169
}
164170
});
@@ -169,20 +175,23 @@ private final class LayerGlobalFocusChangeListener implements ViewTreeObserver.O
169175
public void onGlobalFocusChanged(View oldFocus, View newFocus) {
170176
if (currentKeyView != null) {
171177
currentKeyView.setOnKeyListener(null);
178+
currentKeyView = null;
172179
}
173-
currentKeyView = mChild.findFocus();
174-
if (currentKeyView != null) {
175-
currentKeyView.setOnKeyListener(mLayerKeyListener);
176-
return;
177-
}
178-
View rootFocus = mChild.getRootView().findFocus();
179-
if (rootFocus != null) {
180-
return;
181-
}
182-
mChild.requestFocus();
183-
currentKeyView = mChild.findFocus();
184-
if (currentKeyView != null) {
185-
currentKeyView.setOnKeyListener(mLayerKeyListener);
180+
if (isAttached()) {
181+
currentKeyView = mChild.findFocus();
182+
if (currentKeyView != null) {
183+
currentKeyView.setOnKeyListener(mLayerKeyListener);
184+
return;
185+
}
186+
View rootFocus = mChild.getRootView().findFocus();
187+
if (rootFocus != null) {
188+
return;
189+
}
190+
mChild.requestFocus();
191+
currentKeyView = mChild.findFocus();
192+
if (currentKeyView != null) {
193+
currentKeyView.setOnKeyListener(mLayerKeyListener);
194+
}
186195
}
187196
}
188197
}

0 commit comments

Comments
 (0)