Situation: I'm having a list of countries. Within this lists I'll have a list of cities. I want to represent a cardview for each country that shows the cities.
Country.cs
public class Country
{
public int CountryId { get; set; }
public string Description { get; set; }
public string Flag { get; set; }
public IList<City> Cities { get; set; }
}
City.cs
public class City
{
public int CityId { get; set; }
public string Description { get; set; }
public int Population { get; set; }
}
MainActivity.cs
public class MainActivity : Activity
{
public IList<Country> Countries = new List<Country>();
public IList<City> CitiesBelgium = new List<City>();
public IList<City> CitiesGermany = new List<City>();
RecyclerView recyclerView;
RecyclerView.LayoutManager layoutManager;
CountryAdapter countryAdapter;
protected override void OnCreate(Bundle savedInstanceState)
{
base.OnCreate(savedInstanceState);
// Set our view from the "main" layout resource
SetContentView(Resource.Layout.Main);
PopulateList(); //this will populate the desired lists in this example
recyclerView = FindViewById<RecyclerView>(Resource.Id.recyclerView);
layoutManager = new LinearLayoutManager(this);
recyclerView.SetLayoutManager(layoutManager);
countryAdapter = new CountryAdapter(Countries);
recyclerView.SetAdapter(countryAdapter);
}
}
CountryAdapter.cs
public class CountryAdapter : RecyclerView.Adapter
{
IList<Country> countries;
public override int ItemCount
{
get { return countries.Count; }
}
public CountryAdapter(IList<Country> countries)
{
this.countries = countries;
}
public override void OnBindViewHolder(RecyclerView.ViewHolder holder, int position)
{
CountryViewHolder vh = holder as CountryViewHolder;
vh.Id.Text = countries[position].CountryId.ToString();
vh.Description.Text = countries[position].Description;
}
public override RecyclerView.ViewHolder OnCreateViewHolder(ViewGroup parent, int viewType)
{
View itemView = LayoutInflater.From(parent.Context).
Inflate(Resource.Layout.CountryCardView, parent, false);
CountryViewHolder vh = new CountryViewHolder(itemView);
return vh;
}
}
CountryViewHolder.cs
public class CountryViewHolder : RecyclerView.ViewHolder
{
public TextView Id { get; private set; }
public TextView Description { get; private set; }
public CountryViewHolder(View itemView) : base(itemView)
{
Id = itemView.FindViewById<TextView>(Resource.Id.textViewId);
Description = itemView.FindViewById<TextView>(Resource.Id.textViewDescription);
}
}
This is working and I get a cardview for each country. But what is the best way to get the list of cities in the cardview of the country?
In Xamarin.Forms you can group items. I don't think this is possible with RecyclerView? Example: https://dzone.com/articles/xamarin-forms-grouping-enabled-listview


