I have a Fragment
. There are two radio buttons in it. I am trying to create a TextView
in
this fragment and change its content according to the RadioButton
user checks.
Below you can see my code. My problem is that when I click on radio buttons nothing happens/
Not the toast message nor the setText()
seem to be called.
Please help me out.
Thanks before.
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
final View rootView = inflater.inflate(R.layout.activity_search, container,false);
final LinearLayout l = (LinearLayout)inflater.inflate(R.layout.activity_search, container, false);
final TextView tv = new TextView(container.getContext());
tv.setText("Testing...");
l.addView(tv);
RadioGroup radios = (RadioGroup) rootView.findViewById(R.id.radios);
radios.setOnCheckedChangeListener(new OnCheckedChangeListener() {
@Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
tv.setText("changedText");
l.addView(tv);
Toast.makeText(getActivity(), "zzzz", 2000).show();
switch(checkedId) {
case R.id.rbtn_sell:
tv.setText("changedText");
l.addView(tv);
break;
case R.id.rbtn_rent:
RadioButton radioButton = (RadioButton) rootView.findViewById(checkedId);
Toast.makeText(getActivity(), "zzzz" + radioButton.getText(), 2000).show();
break;
}
}
});
return l;
}
final View rootView = inflater.inflate(R.layout.activity_search, container,false);
final LinearLayout l = (LinearLayout)inflater.inflate(R.layout.activity_search, container, false);
the problem is here. You are inflating twice the same layout and returnin l
, but attach the OnCheckedChangeListener
on the RadioGroup you retrieve with rootView
. It should be
RadioGroup radios = (RadioGroup) l.findViewById(R.id.radios);
instead of
RadioGroup radios = (RadioGroup) rootView.findViewById(R.id.radios);
Also inside onCheckedChanged
you should remove l.addView
otherwise you application wil crash because the TextView
has already as parent l