मुझे यह पता लगाने की आवश्यकता है कि क्या किसी गतिविधि के अंदर कोई दृश्य केंद्रित है और वह क्या दृश्य है। यह कैसे करना है?
जवाबों:
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;
}
किसी कारण के लिए getCurrentFocus () विधि अब उपलब्ध नहीं है; शायद यह पहले से ही पदावनत है, यहाँ काम करने का विकल्प:
View focusedView = (View) yourParentView.getFocusedChild();
getFocusedChild()एक विधि है ViewGroup।
इसके बजाय यह प्रयास करें, सब कुछ अंदर रखें threadऔर आईडी और क्लासनाम लाइव को प्रिंट करें 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 के चक्र में चलता है इसलिए यह अनावश्यक काम के साथ सीपीयू को ओवरफ्लो नहीं करता है।
यदि आप एक टुकड़े में हैं तो आप उपयोग कर सकते हैं
getView().findFocus()