Devo scoprire se una vista è focalizzata all'interno di un'attività e quale vista è. Come fare questo?
Risposte:
Chiama getCurrentFocus()l'attività.
getCurrentFocus(), ma non così affidabile.
activity?.currentFocus
Dalla fonte dell'attività:
/**
* 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;
}
Prova questo invece, metti tutto dentro a threade stampa l' id e il nome della classe live su logcat. Metti semplicemente questo codice nel tuo Activity, nel onCreatemetodo, quindi guarda nel tuo logcatper vedere cosa è attualmente focalizzato.
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()
Tieni presente che questo thread viene eseguito in un ciclo di 100 ms in modo da non sovraccaricare la CPU con lavoro non necessario.
logcatè molto più sicuro.
per qualche motivo il metodo getCurrentFocus () non è più disponibile; probabilmente è già deprecato, ecco l'alternativa funzionante:
View focusedView = (View) yourParentView.getFocusedChild();
getFocusedChild()è un metodo su ViewGroup.
se sei in un frammento puoi usare
getView().findFocus()