Search code examples
androidandroid-checkbox

Enable the Edit text field when checkbox is check


<CheckBox
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:letterSpacing="0.1"
            android:text="Mechanic"
            android:textColor="@color/darkgreen"
            android:textSize="16sp"
            android:paddingRight="25dp"
            android:id="@+id/cbmechanic"
            android:textStyle="bold"/>
Mechaniccb.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
                @Override
                public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                    if (isChecked){
                        Mechanicname.setFocusable(true);
                        Mechanicname.setCursorVisible(true);
                        Mechanicname.setEnabled(true);
                        //Toast.makeText(Mechanic_form.this,"Checked",Toast.LENGTH_SHORT).show();
                    }else {
                        Mechanicname.setText("");
                        Mechanicname.setFocusable(false);
                        Mechanicname.setCursorVisible(false);
                        Mechanicname.setEnabled(false);
                        Toast.makeText(Mechanic_form.this,"Not Checked",Toast.LENGTH_SHORT).show();
                    }
                }
            });

Here is my xml code and following code is java. I want to enable text field when checkbox(Mechaniccb) is clicked but this code works only for one time. If checkbox is check and then unchecked this code is not working and I am unable to edit the edit text field(Mechanicname). Also when i run the application the edit text is still editable even it is unchecked


Solution

  • Add android:enabled="false" to your EditText, then add this :

    Mechaniccb.setOnCheckedChangeListener((buttonView, isChecked) -> {
                if (isChecked) Mechanicname.setEnabled(true);
                else {
                    Mechanicname.setEnabled(false);
                    Mechanicname.getText().clear();
                }
            });