如何找出重点关注的视图?

Fix*_*int 76 android

我需要找出是否有任何视图集中在一个Activity中,以及它是什么视图.这该怎么做?

Kar*_*ran 103

请致电getCurrentFocus()活动.

  • BTW,getCurrentFocus()是一种活动方法,而不是视图. (10认同)
  • ...所以在片段中我们可以使用getActivity().getCurrentFocus().clearFocus()例如.. (3认同)

Tob*_*run 11

来自活动的来源:

   /**
     * 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;
    }
Run Code Online (Sandbox Code Playgroud)


Har*_*jem 11

试试这个,把所有东西都放在 a 中thread,并将idclassname live打印到logcat. 只需将此代码放在您的Activity,onCreate方法中,然后查看您的logcat当前重点。

爪哇

  new Thread(() -> {
        int oldId = -1;
        while (true) {
            View newView= this.getCurrentFocus();
            if (newView != null && newView.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: \t" + idName + "\tClass: \t" + newView.getClass());
            }
            try {
                Thread.sleep(100);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }).start();
Run Code Online (Sandbox Code Playgroud)

科特林

      Thread(Runnable {
            var oldId = -1
            while (true) {
                val newView: View? = this.currentFocus
                if (newView != null && newView.id != oldId) {
                    oldId = newView.id
                    var idName: String = try {
                        resources.getResourceEntryName(newView.id)
                    } catch (e: Resources.NotFoundException) {
                        newView.id.toString()
                    }
                    Log.i(TAG, "Focused Id: \t" + idName + "\tClass: \t" + newView.javaClass)
                }
                try {
                    Thread.sleep(100)
                } catch (e: InterruptedException) {
                    e.printStackTrace()
                }
            }
        }).start()
Run Code Online (Sandbox Code Playgroud)

请注意,此线程以 100 毫秒为周期运行,因此它不会因不必要的工作而使 CPU 溢出。


Pab*_*son 10

如果你在一个片段中,你可以使用

getView().findFocus()
Run Code Online (Sandbox Code Playgroud)


Joh*_*n F 5

由于某种原因,getCurrentFocus()方法不再可用; 可能它已经被弃用了,这里的工作替代方案:

View focusedView = (View) yourParentView.getFocusedChild();
Run Code Online (Sandbox Code Playgroud)

  • @BoredT:`getFocusedChild()` 是 `ViewGroup` 上的一个方法。 (2认同)