Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
293 views
in Technique[技术] by (71.8m points)

android - setting up a RadioGroup programmatically

I'd like to create a custom View which contains a RadioGroup. Inside of the RadioGroup I'd like the RadioButtons to be set up so that the first RadioButton is at the top left, the 2nd one is below that, the third to the right of the 1st one and the 4th one underneath that. In other words, I want to create a group where the radiobuttons are laid out in a square of sorts. I think if I set the orientation of the group to be vertical, then all the radiobuttons will be in a straight line. If, on the other hand, I set the orientation to horizontal, then, again, the radiobuttons will all be in a straight line, going horizontal. Is there a way to do what I want or am I forced to set up two separate RadioGroups, both to horizontal orientation?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Try processing the RadioButtons without the use of RadioGroup.

Wire-up the individual RadioButtons and hold them in an ArrayList<RadioButton>.

List<RadioButton> radioButtons = new ArrayList<RadioButton>();

radioButtons.add( (RadioButton)findViewById(R.id.button1) );        
radioButtons.add( (RadioButton)findViewById(R.id.button2) );
radioButtons.add( (RadioButton)findViewById(R.id.button3) );
etc.

Set an OnCheckedChangeListener for each RadioButton.

for (RadioButton button : radioButtons){

    button.setOnCheckedChangeListener(new OnCheckedChangeListener(){
        @Override
        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
            if (isChecked) processRadioButtonClick(buttonView);
        }   
    });

}

Then create a method to uncheck the unselected RadioButtons.

private void processRadioButtonClick(CompoundButton buttonView){

    for (RadioButton button : radioButtons){

        if (button != buttonView ) button.setChecked(false);
    }

}

Using this approach, the RadioButtons can be located anywhere within the XML layout.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...