Necesito averiguar si alguna vista está enfocada dentro de una actividad y qué vista es. ¿Como hacer esto?
Necesito averiguar si alguna vista está enfocada dentro de una actividad y qué vista es. ¿Como hacer esto?
Respuestas:
Llame getCurrentFocus()a la Actividad.
getCurrentFocus(), pero no es tan confiable.
activity?.currentFocus
De la fuente de actividad:
/**
* 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;
}
por alguna razón, el método getCurrentFocus () ya no está disponible; probablemente ya esté en desuso, aquí la alternativa de trabajo:
View focusedView = (View) yourParentView.getFocusedChild();
getFocusedChild()es un método de ViewGroup.
En su lugar, intente esto, coloque todo dentro de threade imprima la identificación y el nombre de clase en vivo logcat. Simplemente coloque este código dentro de su Activity, en el onCreatemétodo, luego mire en su logcatpara ver qué está enfocado actualmente.
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()
Tenga en cuenta que este hilo se ejecuta en un ciclo de 100 ms para que no desborde la CPU con trabajo innecesario.
si estás en un fragmento puedes usar
getView().findFocus()