Search code examples
androidandroid-listviewandroid-edittext

Need to identify type of View


Android. API 16 (I know, is old but I can't change)

I need to identify the type of view in focus programmatically. I have a thread capable to generate data but not always the correct view is in focus (EditText). I need to check, when the data are ready, if the current view in focus can handle the data. If yes, ok, if not the data are just discarded/lost. I know that one of the possible View in focus can be a ListView.

What is the best way to do so ?

I did try with activity.getCurrentFocus().getContentDescription() but it crash.

Any suggestion ?

Thanks !


Solution

  • To do this you could use instanceof.

    if (activity.getCurrentFocus() instanceof ListView){
        // do whatever
    } else {
        // do other
    }
    

    Another option would be checking for reference equality. If you have a reference to the views you expect could be in focus, simply check each:

    View inFocus = activity.getCurrentFocus()
    if (inFocus == myView){
        // do whatever
    } else if (inFocus == myOtherView){
    
    } else {...}