JAVA重用onTouchListener,用于editText的setOnFocusChangeListener事件

时间:2013-08-21 02:06:45

标签: java android android-layout

    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字段的所有事件,而不进行复制粘贴。

2 个答案:

答案 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);

希望得到这个帮助。