dateField.setOnFocusChangeListener(new OnFocusChangeListener() {
@Override
public void onFocusChange(View v, boolean hasFocus) {
if(!hasFocus && TextUtils.isEmpty(dateField.getText().toString())){
dateField.setText(DateDefaultValue);
} else if (hasFocus && dateField.getText().toString().equals(DateDefaultValue)){
dateField.setText("");
}
else
{btnShowHide.setVisibility(RelativeLayout.VISIBLE);}
if (!hasFocus)
{
if (dateField.getText().length() >0)
btnShowHide.setVisibility(RelativeLayout.INVISIBLE);
}
}
});
我想重新使用setOnFocusChangeListener和onTouchListener的事件,以及我的editText字段的所有事件,而不进行复制粘贴。
答案 0 :(得分:1)
您应该创建一个新类(例如MyListener()),而不是创建匿名内部方法。
class MyListener extends FocusChangeListener{
@Override
public void onFocusChange(View v, boolean hasFocus) {
if(!hasFocus && TextUtils.isEmpty(dateField.getText().toString())){
dateField.setText(DateDefaultValue);
} else if (hasFocus&&dateField.getText().toString().equals(DateDefaultValue)){
dateField.setText("");
}else{
btnShowHide.setVisibility(RelativeLayout.VISIBLE);}
if (!hasFocus && dateField.getText().length() >0)
{
btnShowHide.setVisibility(RelativeLayout.INVISIBLE);
}
}
}
并像这样使用它:dateField.setOnFocusChangeListener(new MyListener());
此外,我对Android API不熟悉,但如果不起作用,请尝试将extends
替换为implements
答案 1 :(得分:0)
您应该只创建一个侦听器并将所有视图事件引用到此
private FocusChangeListener mFocusChangeListener = new OnFocusChangeListener() {
@Override
public void onFocusChange(View v, boolean hasFocus) {
if(v == dateField){....}
else if(v == nameField){....}
if(!hasFocus && TextUtils.isEmpty(dateField.getText().toString())){
dateField.setText(DateDefaultValue);
} else if (hasFocus && dateField.getText().toString().equals(DateDefaultValue)){
dateField.setText("");
}
else
{btnShowHide.setVisibility(RelativeLayout.VISIBLE);}
if (!hasFocus)
{
if (dateField.getText().length() >0)
btnShowHide.setVisibility(RelativeLayout.INVISIBLE);
}
}
}
然后:
dateField.setOnFocusChangeListener(mFocusChangeListener);
希望得到这个帮助。