简体   繁体   中英

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?

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
}

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM