Reputation: 5384
The title already describes what I want to do: I'm working with Xamarin for Android. Now I'd like to have a RadioGroup
and fill it with RadioButton
s via code behind and not via XAML. How can I do this? I don't find any setter...
Why do I need this? My small Android app has a Load button which loads entries from a web service. Each entry should be represented by a RadioButton
so that the user has a flexible selection.
Upvotes: 1
Views: 1565
Reputation: 5384
As an alternative, I've implemented a solution using a ListView
:
protected override void OnCreate(Bundle savedInstanceState)
{
base.OnCreate(savedInstanceState);
SetContentView(Resource.Layout.activity_main);
var toolbar = FindViewById<Toolbar>(Resource.Id.toolbar);
SetSupportActionBar(toolbar);
Speakers = new List<ISpeaker>();
FindViewById<Button>(Resource.Id.loadButton).Click += LoadButtonOnClick;
}
private async void LoadButtonOnClick(object sender, EventArgs e)
{
Speakers = await LoadSpeakersAsync();
var sourceListView = FindViewById<ListView>(Resource.Id.sourceListView);
sourceListView.Adapter = new ArrayAdapter<ISpeaker>(this, Android.Resource.Layout.SimpleListItem1, Speakers);
}
Upvotes: 0
Reputation: 1088
Here's an example I put together for you that creates the Radio Group and Radio Buttons dynamically along with how to determine which button is selected by the user at run-time.
protected override void OnCreate(Bundle savedInstanceState) {
base.OnCreate(savedInstanceState);
var layout = new LinearLayout(this) {
Orientation = Orientation.Vertical
};
// Create Radio Group
var rg = new RadioGroup(this);
layout.AddView(rg);
// Add Radio Buttons to Radio Group
for (int i = 1; i < 6; i++) {
var rb = new RadioButton(this) { Text = $"Radio Button {i}" };
rg.AddView(rb);
}
// Show Radio Button Selected
lblOutput = new TextView(this);
layout.AddView(lblOutput);
rg.CheckedChange += (s, e) => {
lblOutput.Text = $"Radio Button {e.CheckedId} Selected";
};
SetContentView(layout);
}
Output
Upvotes: 1