Kerv
Kerv

Reputation: 179

Disabling the edittext by default by unchecking the checkbox error

I have one question. I want my edittext to be initially disabled. It will be only enabled when I check the checkbox. What is happening is, when i launch the app, the checkbox has no check but i can edit the edittext. To disable the edittext, i have to check then uncheck again the text box. Can you help me?

here is my code:

check1.setOnCheckedChangeListener(new OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView,
    boolean isChecked) {
    if (isChecked) {
        txtbox1.setEnabled(true);
    } else {
        txtbox1.setEnabled(false);
    }
}
});

When using 2 checkboxes for 2 different edittext. My app crashes when pressing the second checkbox. Heres the code:

public void onCreate(Bundle savedInstanceState) {  
super.onCreate(savedInstanceState);  
setContentView(R.layout.order);  
txtbox1= (EditText) findViewById(R.id.editText1);  
button1 = (Button) findViewById(R.id.button1);  
tv = (TextView) findViewById(R.id.editText5);  
txtbox2= (EditText) findViewById(R.id.editText2);
check1 = (CheckBox)findViewById(R.id.checkcheck);
check2 = (CheckBox)findViewById(R.id.checkcheckcheck);
button1.setOnClickListener(new clicker());



check1.setOnCheckedChangeListener(new OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView,
    boolean isChecked) {
    if (isChecked) {
        txtbox1.setEnabled(true);
        txtbox1.setFocusable(true);
    } else {
        txtbox1.setEnabled(false);
        txtbox1.setFocusable(false);
    }
}

});

check2.setOnCheckedChangeListener(new OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView,
    boolean isChecked) {
    if (isChecked) {
        txtbox2.setEnabled(true);
        txtbox2.setFocusable(true);
    } else {
        txtbox2.setEnabled(false);
        txtbox2.setFocusable(false);
    }
}

});

}

Logcat: Logcat

Upvotes: 0

Views: 1249

Answers (3)

Ritesh Gune
Ritesh Gune

Reputation: 16739

In your xml file use android:enabled = "false" for edittext to disable it initially.

or Programatically write txtbox1.setEnabled(false); in your onCreate().

Then use :

check1.setOnCheckedChangeListener(new OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView,
    boolean isChecked) {
    if (isChecked) {
        txtbox1.setEnabled(true);
    } else {
        txtbox1.setEnabled(false);
    }
}

Upvotes: 1

Lia Pronina
Lia Pronina

Reputation: 756

Maybe this will help you:

txtbox1.setKeyListener(null);

Upvotes: 1

bixiaopeng
bixiaopeng

Reputation: 383

do u invoke the txtbox1.setEnabled(false); in the onCreate() ?
the onCheckChanged will not invoked at the very begining.

Upvotes: 1

Related Questions