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?

Upvotes: 4

Views: 1626

Answers (3)

Jeremy
Jeremy

Reputation: 576

To check for a specific class, use

if (v.getClass().equals(TextView.class)) {
  /* ... */
} else if (v.getClass().equals(Spinner.class)) {
  /* ... */
}

As Vucko and Ognian stated, EditText extends TextView, that's why your instanceof doesn't behave as you expected.

Upvotes: 3

Vucko
Vucko

Reputation: 7479

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.

Upvotes: 3

Ognian Gloushkov
Ognian Gloushkov

Reputation: 2659

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
}

Upvotes: 7

Related Questions