Home » Android » android – RadioGroup.setEnabled(false) doesn't work as expected

android – RadioGroup.setEnabled(false) doesn't work as expected

Posted by: admin April 23, 2020 Leave a comment

Questions:

I have used setEnabled(false) to set it unable, but it doesn’t work and after this method, the value of RadioGroup.isEnabled() is false. The value was changed.

The code is from Android Programming Guide.

PS: The Spinner component use the setEnabled(false) as well.

Code is as follows:

import android.app.Activity;
import android.graphics.Color;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.RadioGroup;

public class TestRadioGroup extends Activity {


@Override
public void onCreate(Bundle savedInstanceState) {
    // TODO Auto-generated method stub
    super.onCreate(savedInstanceState);
    setContentView(R.layout.radiogroup);

    final RadioGroup testRadioGroup = (RadioGroup) findViewById(R.id.testRadioGroup);

    final Button changeEnabledButton = (Button) findViewById(R.id.changeEnabledButton);
    changeEnabledButton.setOnClickListener(new OnClickListener() {

        public void onClick(View v) {
            // TODO Auto-generated method stub
            changeEnabled(testRadioGroup);
        }
    });

    final Button changeBgColorButton = (Button) findViewById(R.id.changeBackgroundColorButton);
    changeBgColorButton.setOnClickListener(new OnClickListener() {

        public void onClick(View v) {
            // TODO Auto-generated method stub
            changeBgColor(testRadioGroup);
        }
    });

}

protected void changeBgColor(RadioGroup testRadioGroup) {
    // TODO Auto-generated method stub
    testRadioGroup.setBackgroundColor(Color.BLUE);
}

protected void changeEnabled(RadioGroup testRadioGroup) {
    // TODO Auto-generated method stub
    if (testRadioGroup.isEnabled()) {
        testRadioGroup.setEnabled(false);
    } else {
        testRadioGroup.setEnabled(true);
    }
}

}

How to&Answers:

use the following method:

for (int i = 0; i < testRadioGroup.getChildCount(); i++) {
    testRadioGroup.getChildAt(i).setEnabled(false);
}

Answer:

Views can be compose by multiple touchable elements. You have to disable them all, like this:

for(View lol : your_spinner.getTouchables() ) {
    lol.setEnabled(false);
}

If it is a simple one since it also returns itself:

Find and return all touchable views that are descendants of this view, possibly including this view if it is touchable itself.

View#getTouchables()

Answer:

You can’t use the following code;

for(View lol : your_spinner.getTouchables() ) {
    lol.setEnabled(false);
}

Once the views has disabled, there is no touchable child/descentant views anymore.