简体   繁体   中英

How to enable a button programmatically when it is disabled in the layout

I'm new to android and I don't know more about it. For practice I was manipulating with spinners, buttons and its attribute.

I have 4 spinners and 1st spinner decides 2nd spinner values and so on. I have a button (android:enabled ="false" in xml) that is located below the 4th spinner and it has a click listener, its click event shows toast about what you select in all spinners.

All spinner's values are in string-array and I want to check and validate all spinners. If any of the spinner is not selected 1st index of array, then button will be enabled otherwise will be disabled.

I have tried many times but not getting expected results. Can anyone help to solve my problem?

Here is my code for button and spinner validation:

public boolean isDefaultValue(Spinner spinner){
    if (spinner.getSelectedItemPosition() == 0){
        resultButton.setEnabled(false);
    } else {
        resultButton.setEnabled(true);
    }
    return false;
}
‎
resultButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            if (isDefaultValue(sp4)) {
                Toast.makeText(getApplicationContext(), "Country : " + sp1.getSelectedItem().toString() + "\n" +
                        "State : " + sp2.getSelectedItem().toString() + "\n" +
                        "City : " + sp3.getSelectedItem().toString() + "\n" +
                        "Area : " + sp4.getSelectedItem().toString(), Toast.LENGTH_LONG).show();
            }
}
 });

Your method isDefaultValue(Spinner) would always return a false irrespective of button being enabled or not, and hence never raises the toast.

Additionally your description reads:

If any of them spinner is not selected 1st index of array then button will be enabled

But according to the method isDefaultValue(Spinner) , the button will be enabled only when the spinner is not in 1st index of array (0) .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM