我需要找出在Activity中是否有任何聚焦的视图以及它是哪个视图。如何做到这一点?
尝试使用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: \t" + idName + "\tClass: \t" + 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: \t" + idName + "\tClass: \t" + newView.javaClass)
}
try {
Thread.sleep(100)
} catch (e: InterruptedException) {
e.printStackTrace()
}
}
}).start()
请注意,此线程每100毫秒运行一次,以避免不必要的工作过载CPU。
logcat
更加安全。 - Haroun Hajem从活动来源:
/**
* 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;
}
getView().findFocus()
由于某些原因,getCurrentFocus()方法不再可用;可能已经被弃用了,在这里提供一个可用的替代方案:
View focusedView = (View) yourParentView.getFocusedChild();
getFocusedChild()
是ViewGroup
的一个方法。 - gnufViewGroup有一个非常方便的方法,可以检索到当前被聚焦的子视图:
ViewGroup.getFocusedChild()
getCurrentFocus()
,但不是很可靠。 - Eido95activity?.currentFocus
- Mohammad Reza Khahani(v.context as? Activity)?.currentFocus
。 - CoolMind