IT TIP

How to find out which view is focused?

itqueen 2020. 10. 21. 22:15
반응형

How to find out which view is focused?


I need to find out if any view is focused inside an Activity and what view it is. How to do this?


Call getCurrentFocus() on the Activity.


From the source of Activity:

   /**
     * Calls {@link android.view.Window#getCurrentFocus} on the
     * Window of this Activity to return the currently focused view.
     * 
     * @return View The current View with focus or null.
     * 
     * @see #getWindow
     * @see android.view.Window#getCurrentFocus
     */
    public View getCurrentFocus() {
        return mWindow != null ? mWindow.getCurrentFocus() : null;
    }

for some reason getCurrentFocus() method isn't available anymore; probably it's deprecated already, here the working alternative:

View focusedView = (View) yourParentView.getFocusedChild();

Just put this inside your Activity inside the onCreate method then look into your logcat to see what is currently focused.

  new Thread(() -> {
        int oldId = -1;
        while (true) {
            View view = this.getCurrentFocus();
            if (view != null && view.getId() != oldId) {
                oldId = view.getId();
                String idName = "";
                try {
                   idName = getResources().getResourceEntryName(newView.getId());
                 } catch (Resources.NotFoundException e) {
                   idName = String.valueOf(newView.getId());
                 }
                Log.i(TAG, "Focused Id: " + idName + " Class: " + view.getClass());
            }
            try {
                Thread.sleep(100);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }).start();

Be aware this thread runs in a 100ms cycle so it doesn't overflow the CPU with unnecessary work.


if you are in a fragment you can use

getView().findFocus()

ViewGroup has quite convenient method for retrieving focused child:

ViewGroup.getFocusedChild()

참고URL : https://stackoverflow.com/questions/5352209/how-to-find-out-which-view-is-focused

반응형