我需要找出是否有一个活动集中在任何视图,它是什么视图。这该怎么做?
Answers:
调用getCurrentFocus()活动。
activity?.currentFocus
从活动的来源:
/**
* 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;
}
由于某种原因,getCurrentFocus()方法不再可用;可能已经过时了,这里是可行的替代方法:
View focusedView = (View) yourParentView.getFocusedChild();
getFocusedChild()是的方法ViewGroup。
改用此方法,将所有内容放到a内thread,并实时将id和classname打印到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: " + idName + " Class: " + newView.getClass());
}
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}).start();
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: " + idName + " Class: " + newView.javaClass)
}
try {
Thread.sleep(100)
} catch (e: InterruptedException) {
e.printStackTrace()
}
}
}).start()
请注意,此线程以100ms的周期运行,因此不会因不必要的工作而使CPU溢出。
如果您处在碎片中,则可以使用
getView().findFocus()