Search code examples
androidkotlincastingandroid-edittext

EditText is a TextView when checking type


I'm using this line to check on a number of views in my app and get the values associated with them, as input by the user. Every other view (odd) is a text view that's used as a title for the following view. These are created dynamically at runtime, and so I've collected the IDs into an arrayList to use in the following loop:

for(id in data.orEmpty()) {
                val mView = findViewById<View>(id)
                if (mView is TextView) {
                    Log.d("BEAU - ", "WOOT! ID number $id TextView - ${mView.text}")
                }
                if (mView is EditText) {
                    Log.d("BEAU - ", "WOOT! ID number $id EditText - ${mView.text}")
                }
                if (mView is RatingBar) {
                   Log.d("BEAU - ", "WOOT! ID number $id RatingBar - ${mView.numStars}")
                }
            }

The problem I'm having is that every EditText is being counted as both a TextView and an EditText; and so I'll have something like this:

D/BEAU -: WOOT! ID number 1 TextView - General EditText

D/BEAU -: WOOT! ID number 2 TextView - Hello World

D/BEAU -: WOOT! ID number 2 EditText - Hello World

However, all of the other things (like the rating bar) work perfectly. So, the question is, why is EditText passing a type check for text view; and is there something I can do to check for only text views and not text views and edit texts in the first if statement?

EDIT:

Temporarily, I've been able to check against EditTexts when checking for TextViews. I've done this like so: if (mView is TextView && mView !is EditText) {} But, is this right to do, and if so why should I have to do it like this?


Solution

  • It's because EditText is a subclass of TextView, so this will give you true -

    EditText is TextView 
    

    In EditText class you can see -

    class EditText extends TextView { ... }