Reputation: 4421
Why is the EditText instanceof call not working but TextView instanceof call is?
Can I solve this with generics or other better way?
public class MyActivity extends ActionBarActivity
...
@Override
public void updateView() {
updateField(noteEditText, vault.getNote());
updateField(categoryTextView, category.getName());
}
private void updateField(View current, String data) {
if(current instanceof EditText && data.equals(((EditText) current).getText())) {
((EditText) current).setText(data);
} else if(current instanceof TextView && data.equals(((TextView) current).getText())) {
((TextView) current).setText(data);
}
}
...
Upvotes: 0
Views: 248
Reputation: 3683
Another way :
try {
((EditText) current).setText(data);
} catch (Exception e){
// Not an EditText
try {
((TextView) current).setText(data);
} catch (Exception e){
// Not a textView
}
}
Upvotes: 0
Reputation: 3522
EditText.getText() does not return a String
but an Editable
object, this is the reason why the first check always fails. Just call toString()
on the result of ((Editable)current).getText()
:
if(current instanceof EditText && data.equals(((EditText) current).getText().toString())) {
((EditText) current).setText(data);
} else if(current instanceof TextView && data.equals(((TextView) current).getText().toString())) {
((TextView) current).setText(data);
}
Upvotes: 3