반응형
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
반응형
'IT TIP' 카테고리의 다른 글
What is COM (Component Object Model) in a nutshell? (0) | 2020.10.21 |
---|---|
Should I use JavaDoc deprecation or the annotation in Java? (0) | 2020.10.21 |
How to create a nested list in reStructuredText? (0) | 2020.10.21 |
java compiled classes contain dollar signs (0) | 2020.10.21 |
Python argparse mutual exclusive group (0) | 2020.10.21 |