Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android detects instanceof EditText and instanceof TextView as the same

I have dynamically created Layout. It has some edittexts, textview, spinners, etc.

After it, I have to get the info I introduce on those views.

So Im doing something like this

for(int i=0;i <= childs;i++){
        View v=parent.getChildAt(i);
             if (v instanceof TextView) {
                //do something
            }
            else if (v instanceof EditText) {
               //do OTHER thing
            }

The problem here is that Android detects v always as TextView when the View is either TextView or Edittext (I have no problem with spinners or button).

How can I solve this?

like image 657
Daniel Arteaga Iriarte Avatar asked Dec 11 '22 14:12

Daniel Arteaga Iriarte


2 Answers

That's because EditText extends TextView.

switch the order of checking:

if (v instanceof EditText) {
     //do something
} else if (v instanceof TextView) {
     //do OTHER thing
}
like image 194
Ognian Gloushkov Avatar answered Dec 13 '22 03:12

Ognian Gloushkov


Switch the order of the if statements. Put the if (v instanceof EditText) on the top so it checks that one first. The reason for this is that EditText directly extends (it would be the same if it were indirect) TextView and thus when something is an EditText, it automatically is the TextView as well, and therefore instanceof returns true there as well.

like image 29
Vucko Avatar answered Dec 13 '22 03:12

Vucko