从 edittext 启用的按钮

Button enabled from edittext

我正在尝试启用一个按钮,但首先我想检查 editText 是否有内容,然后再启用该按钮。这是我的代码。最好的解决方案应该是什么?

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    // Inflate the layout for this fragment
    rootView =inflater.inflate(R.layout.fragment_sign_up_part_two, container, false);
    app();
    return rootView;
}

public void app(){
    etCorreo = (EditText)rootView.findViewById(R.id.tvCorreoUsuario);
    etPassword = (EditText)rootView.findViewById(R.id.tvPassword);
    btnRegistrarse = (Button)rootView.findViewById(R.id.btnRegistro);
    events();
}

public void events(){
    if(validate()){
        btnRegistrarse.setEnabled(true);
        btnRegistrarse.setClickable(true);
    }
}

public Boolean validate(){
    correo = etCorreo.getText().toString().trim();
    pass = etPassword.getText().toString().trim();

    if(correo.isEmpty()) return false;
    if(pass.isEmpty()) return false;

    return true;
}

这是我的 xml

<Button
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:text="@string/btn_registrarse"
    android:id="@+id/btnRegistro"
    android:enabled="false"
    android:layout_gravity="center_horizontal"
    android:background="@color/background_color"
    android:layout_margin="10dp"
    />

添加addTextChangedListener后,尝试使用afterTextChangededittext的方法。例如:

EditText editText = (EditText)findViewById(R.id.yourEditText);
    editText.addTextChangedListener(new TextWatcher(){
        public void afterTextChanged(Editable s) {
            if(s.toString().length() > 0)
                your_button.setEnable(true);
            else
                your_button.setEnable(false);
        }
        public void beforeTextChanged(CharSequence s, int start, int count, int after){}
        public void onTextChanged(CharSequence s, int start, int before, int count){}
    });

希望对你有所帮助。 :)

你可以这样做-

boolean isTextNotEmpty=validate();
if(isTextNotEmpty){
btnRegistrarse.setEnabled(true);
}

您可以使用TextWatcher 来监控EditText 中Text 的变化。 示例:

textMessage.addTextChangedListener(new TextWatcher(){
    public void afterTextChanged(Editable s) {
        // check the changing of text and decide to enable/disable button here
    }
    public void beforeTextChanged(CharSequence s, int start, int count, int after){}
    public void onTextChanged(CharSequence s, int start, int before, int count){}
}); 

这个question也许有用

//try this code, you have enter any value edittext then button visible
@Override
    public void onTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) {

        //check data equal or not or any other logic....
            login.setEnabled(true);



    }