Reputation: 779
I want to add radio buttons based on some value. Value defines the total number of radio button that i have to show. Currently i am adding two radio button dynamically but this is not a proper solution for me to adding the Radio buttons. If i have to show 10 radio buttons for this code i have to create 10 instances of radio buttons. Can anyone please suggest me how can i achieve this.
code:-
class FragmentQues : Fragment() {
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?): View? {
return inflater.inflate(R.layout.fragmentques_layout, container, false)
}
@SuppressLint("ResourceType")
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
// Create RadioButton programmatically
val radioButton1 = RadioButton(activity)
radioButton1.layoutParams= LinearLayout.LayoutParams(
ViewGroup.LayoutParams.WRAP_CONTENT,
ViewGroup.LayoutParams.WRAP_CONTENT)
radioButton1.setText("No")
radioButton1.id = 1
val radioButton2 = RadioButton(activity)
radioButton2.layoutParams = LinearLayout.LayoutParams(
ViewGroup.LayoutParams.WRAP_CONTENT,
ViewGroup.LayoutParams.WRAP_CONTENT)
radioButton2.setText("Yes")
radioButton2.id = 2
profile_radio_group.addView(radioButton1)
profile_radio_group.addView(radioButton2)
profile_radio_group.setOnCheckedChangeListener { group, checkedId ->
if (checkedId ==1){
// Some code
}else{
// Some code
}
}
}
}
Upvotes: 0
Views: 1024
Reputation: 871
Well, This can be done through a simple for loop
class FragmentQues : Fragment() {
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?): View? {
return inflater.inflate(R.layout.fragmentques_layout, container, false)
}
@SuppressLint("ResourceType")
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
val value = 2;
// If you have custom text for each button you have to define them in a list
val textList = listOf("No", "Yes")
for(i in 0 until value){
// Create RadioButton programmatically
val radioButton = RadioButton(activity)
radioButton.layoutParams= LinearLayout.LayoutParams(
ViewGroup.LayoutParams.WRAP_CONTENT,
ViewGroup.LayoutParams.WRAP_CONTENT)
radioButton.setText(textList[i])
radioButton.id = i
profile_radio_group.addView(radioButton)
}
profile_radio_group.setOnCheckedChangeListener { group, checkedId ->
if (checkedId ==1){
// Some code
}else{
// Some code
}
}
}
Upvotes: 1