如果启用了错误,如何检查TextInputLayout

时间:2015-08-07 11:39:40

标签: android android-design-library

如果editText1是焦点并且editTextWrapper已经显示错误并且我移动了frocus(例如editText2),则errorMessage会闪烁一下(因为focusListener withl再次启用它)并且会出现小动画故障。

有没有办法检查是否启用了TextInputLayout错误(或者是否知道显示错误的其他方式,除了对我的班级进行外部验证外?

public class NoteCreateFragment extends Fragment{

@Bind(R.id.edit_text1) EditText editText1;
@Bind(R.id.edit_text2) EditText editText2;
@Bind(R.id.edit_text_wrapper) TextInputLayout editTextWrapper;


@Override
public void onCreate(Bundle savedInstanceState){
    super.onCreate(savedInstanceState);
    setHasOptionsMenu(true);


}


@Override
public View onCreateView(
    LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState
){
    View view = inflater.inflate(R.layout.fragment_note_create, container, false);
    ButterKnife.bind(this, view);
    editText1.addTextChangedListener(textWatcher);
    editText1.setOnFocusChangeListener(focusListener);
    return view;
}


@Override
public void onDestroyView(){

    super.onDestroyView();
    ButterKnife.unbind(this);
}



private void createTask(){
    String text1 = editText1.getText().toString();
    if(text1.isEmpty()){

        editTextWrapper.setError("Please enter task name");
    } 
}





private TextWatcher textWatcher = new TextWatcher(){

    @Override
    public void beforeTextChanged(CharSequence s, int start, int count, int after){

    }


    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count){
        if(s.length() > 3){ editTextWrapper.setErrorEnabled(false); }
    }


    @Override
    public void afterTextChanged(Editable s){

    }
};
private View.OnFocusChangeListener focusListener = new View.OnFocusChangeListener(){

    @Override
    public void onFocusChange(View v, boolean hasFocus){
        if(!hasFocus && editText1.getText().toString().length() < 1){
            editTextWrapper.setErrorEnabled(true);
            editTextWrapper.setError("Please enter task name");
            Log.e("TextInputLayout", editTextWrapper.getEditText().getError().toString());
        }
    }
};

}

1 个答案:

答案 0 :(得分:3)

不要在运行时更改setErrorEnabled(),以显示/隐藏错误。使用setError(message)显示错误,使用setError(null)隐藏错误。因此

if(!TextUtils.isEmpty(textInputLayout.getError())

如果错误是有效的,则返回true,否则返回