Preciso descobrir se alguma visão está focada dentro de uma atividade e qual é. Como fazer isso?
Preciso descobrir se alguma visão está focada dentro de uma atividade e qual é. Como fazer isso?
Respostas:
Ligue getCurrentFocus()para a atividade.
getCurrentFocus(), mas não tão confiável.
activity?.currentFocus
Da fonte de atividade:
/**
* 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 algum motivo, o método getCurrentFocus () não está mais disponível; provavelmente já está obsoleto, aqui está a alternativa de trabalho:
View focusedView = (View) yourParentView.getFocusedChild();
getFocusedChild()é um método ativado ViewGroup.
Tente fazer isso, coloque tudo dentro de um threade imprima o id e o nome da classe ao vivo logcat. Basta colocar este código dentro do seu Activity, no onCreatemétodo e depois olhar para o seu logcatpara ver o que está focado no momento.
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()
Esteja ciente de que este thread é executado em um ciclo de 100ms para não sobrecarregar a CPU com trabalho desnecessário.
se você estiver em um fragmento, você pode usar
getView().findFocus()