Search code examples
androidandroid-layoutandroid-checkedtextview

enable and disable the edittext in android onclick of CheckBox


'

//this is first checkbox on click this it will enable f1 & n1

check1=(CheckBox)findViewById(R.id.checkbox1);

//to disable the editext1

        f1=(EditText)findViewById(R.id.editTextf1);
         f1.setEnabled(false);
        f1.setInputType(InputType.TYPE_NULL);
        f1.setFocusable(false);
         n1=(EditText)findViewById(R.id.editTextn1);
         n1.setEnabled(false);
        n1.setInputType(InputType.TYPE_NULL);
        n1.setFocusable(false);

//this is second checkbox on click this it will enable f2 & n2

        check2=(CheckBox)findViewById(R.id.checkBox2);

//to disable the editext2 f2

        f2=(EditText)findViewById(R.id.editTextf2;
        f2.setEnabled(false);
        f2.setInputType(InputType.TYPE_NULL);
        f2.setFocusable(false);

//to disable the editext2 n2

        n2=(EditText)findViewById(R.id.editTextn2);
        n2.setEnabled(false);
        n2.setInputType(InputType.TYPE_NULL);
        n2.setFocusable(false);

        btnfinal=(Button)findViewById(R.id.button_final_submission);

//to enable the editext1 f1 & n1

        if (check1.isChecked()) {
            f1.setEnabled(true);
            f1.setInputType(InputType.TYPE_CLASS_TEXT);
            f1.setFocusable(true);

            n1.setEnabled(true);
            n1.setInputType(InputType.TYPE_CLASS_TEXT);
            nc1.setFocusable(true);


        }

//to enable the editext1 f2 & n2

        if (check2.isChecked()) {
            f2.setEnabled(true);
            f2.setInputType(InputType.TYPE_CLASS_TEXT);
            f2.setFocusable(true);

            n2.setEnabled(true);
            n2.setInputType(InputType.TYPE_CLASS_TEXT);
            n2.setFocusable(true);


        }**

'


Solution

  • You need to set listeners on your checkboxes, and then have to capture the events like when checkbox is checked and when check is removed to make your editexts work the way you want.Your current code will execute and it will take care of no future events because no listener is registered to capture the events. The Simplest way to start is

    CheckBox someCheckBox= (CheckBox) findViewById (R.id.someID);
    someCheckBox.setOnClickListener(new OnClickListener() {
    
          @Override
          public void onClick(View v) {
            if (((CheckBox) v).isChecked()) {
                    //CODE TO MAKE THE EDITTEXT ENABLED         
            }
            else 
               //CODE TO MAKE THE EDITTEXT DISABLED     
    
          }
        });
    

    However there are other ways too,to perform this task, but you can kick off with this right away.