Emsal Emsal - 1 month ago 6
Android Question

Check if dynamically added TextEdit has text in it Android

I'm overriding the onFocusChanged to pinpoint the TextEdit that just lost focus. The point is to remove this TextEdit if it doesn't have any text in it. The problem is that the "if((EditText..." is not valid(cannot resolve method 'getText()') I've tried casting it to tell that it's a EditText view.

listItemsView is the id of the LinearLayout and listItems is an ArrayList of EditText.

@Override
public void onFocusChange(View view, boolean hasFocus) {
if (!hasFocus) {

int removeCurrent = listItems.indexOf(this)+1;
// code to execute when EditText loses focus
if((EditText)view.getText().equals("")) {

}
listItemsView.removeViewAt(removeCurrent);
listItems.remove(removeCurrent);
}
}
});


I've also tried:

if((EditText)listItemsView.getChildAt(removeCurrent).getText().equals(""))


same result.

Answer

When you want to cast a value to a type, you do this:

(T)V

Where T is the type you want to cast to, and V is the value.

So far so good?

In your code,

(EditText)view.getText().equals("")

What is V and what is T? The answer might surprise you! T is obviously EditText, but V here is actually view.getText().equals("")!

In other words, you did not cast view to EditText. That's why the compiler can't find a method named getText. To tell the compiler to specifically cast view, add parentheses:

((EditText)view).getText().equals("")