【发布时间】:2011-03-18 12:51:00
【问题描述】:
我需要找出是否有任何视图集中在 Activity 中,以及它是什么视图。如何做到这一点?
【问题讨论】:
标签: android
我需要找出是否有任何视图集中在 Activity 中,以及它是什么视图。如何做到这一点?
【问题讨论】:
标签: android
在 Activity 上调用 getCurrentFocus()。
【讨论】:
getCurrentFocus(),但不是那么可靠。
activity?.currentFocus
来自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;
}
【讨论】:
试试这个,把所有东西都放在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 更安全。
由于某种原因,getCurrentFocus() 方法不再可用;可能它已经被弃用了,这里是可行的替代方案:
View focusedView = (View) yourParentView.getFocusedChild();
【讨论】:
getFocusedChild() 是ViewGroup 上的一个方法。
如果你在一个片段中你可以使用
getView().findFocus()
【讨论】:
ViewGroup 有很方便的方法来获取焦点子:
ViewGroup.getFocusedChild()
【讨论】: