Skip to content

Instantly share code, notes, and snippets.

@feromakovi
Created October 12, 2016 14:22
Show Gist options
  • Save feromakovi/7d2266a58922b115e49a793ae9f81d42 to your computer and use it in GitHub Desktop.
Save feromakovi/7d2266a58922b115e49a793ae9f81d42 to your computer and use it in GitHub Desktop.
Watcher class used to handle and observe focus changes of selected views. If none of these views has focus, defined fallback view will try to acquire focus. Helpful when code app for device with keyboard/arrows navigation.
/**
* Created by feromakovi <feromakovi@gmail.com> on 12/10/16.
*/
@UiThread
public final class FocusWatcher implements View.OnFocusChangeListener {
private final List<WeakReference<View>> mWatchedViews = new ArrayList<>();
private WeakReference<View> mFallBackView;
public FocusWatcher(@NonNull final View fallback) {
setFallbackView(fallback);
}
public FocusWatcher(@NonNull final View fallback, @NonNull @Size(min = 1) final View... viewsToWatch) {
this(fallback);
addViews(viewsToWatch);
}
public void setFallbackView(@NonNull final View fallback) {
this.mFallBackView = new WeakReference<View>(fallback);
}
public synchronized boolean addViews(@NonNull @Size(min = 1) final View... watchedViews) {
boolean result = true;
for (View v : watchedViews) {
v.setOnFocusChangeListener(this);
result &= mWatchedViews.add(new WeakReference<View>(v));
}
return result;
}
public synchronized void clearViews() {
for (WeakReference<View> view : mWatchedViews) {
view.clear();
}
mWatchedViews.clear();
}
private boolean isOneOfWatchedViewsFocused() {
boolean result = false;
for (WeakReference<View> weak : mWatchedViews){
final View view = weak.get();
result |= (view != null && view.hasFocus());
}
return result;
}
@Override
public void onFocusChange(View v, boolean hasFocus) {
if (!isOneOfWatchedViewsFocused()){
final View fallbackView = mFallBackView.get();
if (fallbackView != null){
fallbackView.requestFocus();
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment