Callback with extended EditText

443 Views Asked by At

I'm trying to create a custom EditText that provides an onLostFocus event. However, I can't get my head around how I tell the custom class what method to run when the focus is lost.

This is my extended EditText:

public class smtyEditText extends EditText {    
    public smtyEditText(Context context) {
        super(context);
    }

    public smtyEditText(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public smtyEditText(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
    }

    public void setFocusChangeListener() {
        this.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            public void onFocusChange(View v, boolean hasFocus) {
                if (!hasFocus) {
                    // notify the relevant activity, probably passing it some parameters like what instance of smtyEditText triggered the event.    
                }
            }
        });
    }
}

The intention of the setFocusChangeListener function was that from any given activity I could do something like:

public class AddMeal extends ActionBarActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_add_meal);

        EditText etMealName = (EditText) findViewById(R.id.txtmealName);
        etMealName.setFocusChangeListener(this.fieldLostFocus)
    }

    // then
    public void fieldLostFocus(eventSource) {
        // run some kind of validation on the field text.
    }
}

Clearly I'm "code paraphrasing" here. I also get that Interfaces, and some other "EventNotifier" class might be needed. These are the resources I've tried to decipher so far:

But for whatever reason I can't crystallize what is needed. Do you have any suggestions on how I can achieve this?

1

There are 1 best solutions below

1
pzulw On BEST ANSWER

You don't need the inheritance... it only adds an unnecessary layer of indirection. Just add the focus change handler in your activity.

public class AddMeal extends ActionBarActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_add_meal);

        EditText etMealName = (EditText) findViewById(R.id.txtmealName);
        etMealName.setFocusChangeListener(new View.OnFocusChangeListener() {
        public void onFocusChange(View v, boolean hasFocus) {
            if (!hasFocus) {
                // call method to handle loss of focus 
            }
        }
    });
    }

    // then
    public void fieldLostFocus(eventSource) {
        // run some kind of validation on the field text.
    }
}