So I have a radio group with 2 radio buttons, when user select the first one it's going to display a text under the radio group, if user selects the second one it's going to display different message on the same area. It's really easy to do this with Toast but I don't want to do it with Toast message.
public void onActivityCreated (Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
Button rb1 = (Button) getActivity().findViewById(R.id.radioButton1);
Button rb2 = (Button) getActivity().findViewById(R.id.radioButton2);
rb1.setOnClickListener(next_Listener);
rb2.setOnClickListener(next_Listener);
}
private OnClickListener next_Listener = new OnClickListener() {
public void onClick(View v) {
RadioGroup radio_grp=(RadioGroup)getActivity().findViewById(R.id.radio_grp);
RadioButton rb1=(RadioButton)getActivity().findViewById(R.id.radioButton1);
RadioButton rb2=(RadioButton)getActivity().findViewById(R.id.radioButton1);
if(rb1.isChecked() == true) {
// display text if they click 1st button
}
if (rb2.isChecked()) == true {
// display text if they click 2nd button
}
}
}
Since RadioButton extends the Button class, you can implement a ClickListener.
You can also implement an onCheckedChangedListener(), but that would require that no value was set by default.
This is explained due to the fact that the onCheckedChangedListener() only triggers when you change between buttons and if one is already selected, you would have no trigger for that button.
Consider you have your TextView defined. You can do it with the following :
public void onActivityCreated (Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
TextView yourTextView = (TextView) findViewById(R.id.your_text_view);
RadioGroup radio_grp= (RadioGroup) getView().findViewById(R.id.radio_grp);
RadioButton rb1 = (RadioButton) getView().findViewById(R.id.radioButton1);
RadioButton rb2 = (RadioButton) getView().findViewById(R.id.radioButton1);
View.OnClickListener button1Listener = new View.OnClickListener() {
public void onClick(View v) {
yourTextView.setText("you have touched button1");
}
};
View.OnClickListener button2Listener = new View.OnClickListener() {
public void onClick(View v) {
yourTextView.setText("you have touched button2");
}
};
rb1.setOnClickListener(button1Listener);
rb2.setOnClickListener(button2Listener);
}
@EDIT
If the RadioGroup and respective RadioButtons are inside the Fragment layout, you should find their views using getView().findViewById()
instead of getActivity().findViewById()
Change the code to this :
RadioGroup radio_grp= (RadioGroup) getView().findViewById(R.id.radio_grp);
RadioButton rb1 = (RadioButton) getView().findViewById(R.id.radioButton1);
RadioButton rb2 = (RadioButton) getView().findViewById(R.id.radioButton2);