使用扩展的EditText进行回调

时间:2015-06-23 19:41:53

标签: android callback custom-controls

我正在尝试创建一个提供EditText事件的自定义onLostFocus。但是,我无法理解如何告诉自定义类在焦点丢失时运行什么方法。

这是我的扩展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.    
                }
            }
        });
    }
}

setFocusChangeListener函数的意图是从任何给定的活动中我可以做类似的事情:

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.
    }
}

显然我在这里是“代码释义”。我也得到了接口,可能还需要其他一些“EventNotifier”类。这些是我到目前为止试图破译的资源:

但无论出于何种原因,我无法明确所需要的东西。您对我如何实现这一目标有什么建议吗?

1 个答案:

答案 0 :(得分:1)

您不需要继承......它只会添加一个不必要的间接层。只需在活动中添加焦点更改处理程序。

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.
    }
}