ฉันต้องการทราบว่ามุมมองใดที่มุ่งเน้นในกิจกรรมและมุมมองนั้นเป็นอย่างไร ต้องทำอย่างไร?
ฉันต้องการทราบว่ามุมมองใดที่มุ่งเน้นในกิจกรรมและมุมมองนั้นเป็นอย่างไร ต้องทำอย่างไร?
คำตอบ:
โทรหาgetCurrentFocus()กิจกรรม
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;
}
ลองนี้แทนใส่ทุกอย่างภายในthreadและพิมพ์รหัสและClassNamelogcatมีชีวิตอยู่เพื่อ เพียงใส่รหัสนี้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()
โปรดทราบว่าเธรดนี้ทำงานในรอบ 100ms ดังนั้นจึงไม่ทำให้ CPU ล้นไปด้วยการทำงานที่ไม่จำเป็น
logcatนั้นปลอดภัยกว่ามาก
ด้วยเหตุผลบางประการเมธอด getCurrentFocus () ไม่สามารถใช้งานได้อีกต่อไป อาจจะเลิกใช้แล้วทางเลือกที่ใช้งานได้ที่นี่:
View focusedView = (View) yourParentView.getFocusedChild();
getFocusedChild()เป็นวิธีการบนViewGroup.
หากคุณอยู่ในส่วนที่คุณสามารถใช้ได้
getView().findFocus()
ViewGroup มีวิธีที่ค่อนข้างสะดวกในการดึงข้อมูลเด็กที่มุ่งเน้น:
ViewGroup.getFocusedChild()