ALIE
ALIE

Reputation: 71

Coloring the elements of Listview

I want to color the background of the first item in listview .

Where it takes a different color from the rest of the elements of listView

Upvotes: 1

Views: 181

Answers (1)

Junior Jiang
Junior Jiang

Reputation: 12723

In Xamarin Android , we can custom a Adapter for ListView to achieve that . Modify GetView method to set background color when position == 0 as follow :

public override View GetView(int position, View convertView, ViewGroup parent)
{
    var item = items[position];

    View view = convertView;
    if (view == null) // no view to re-use, create new
        view = context.LayoutInflater.Inflate(Resource.Layout.CustomView, null);
    view.FindViewById<TextView>(Resource.Id.Text1).Text = item.Heading;
    view.FindViewById<TextView>(Resource.Id.Text2).Text = item.SubHeading + " items";
    view.FindViewById<ImageView>(Resource.Id.Image).SetImageResource(item.ImageResourceId);

    // Here set background color when position == 0 

    if (position == 0)
    {
        view.SetBackgroundColor(Android.Graphics.Color.Red);
    }

    return view;
}

The effect :

enter image description here

In Xamarin Forms, we can create a Item class for listview each cell .

public class Item
{
    public Color DefaultColor { set; get; }
    public string DisplayName { set; get; }
}

Then create a ViewModel class as follow :

public class ViewModel
{
    public List<Item> Items { set; get; }
    public ViewModel()
    {
        Items = new List<Item>();
        Items.Add(new Item() { DefaultColor = Color.Red, DisplayName = "First Item" });
        Items.Add(new Item() { DisplayName = "Second Item" }) ;
        Items.Add(new Item() { DisplayName = "Third Item" });
        Items.Add(new Item() { DisplayName = "Fourth Item" });
        Items.Add(new Item() { DisplayName = "Fifth Item" });
    }
}

In Xaml , ListView setted as follow :

<ListView x:Name="EmployeeView" VerticalOptions="CenterAndExpand">
    <ListView.ItemTemplate>
        <DataTemplate>
            <ViewCell>
                <StackLayout  BackgroundColor="{Binding DefaultColor}">
                    <Label Text="{Binding DisplayName}" VerticalOptions="Center" HorizontalOptions="CenterAndExpand"/>
                </StackLayout>
            </ViewCell>
        </DataTemplate>
    </ListView.ItemTemplate>
</ListView>

Last setting ViewModel for ListView in ContentPage :

public MainPage()
{
    InitializeComponent();
    var viewModel = new ViewModel();
    EmployeeView.ItemsSource = viewModel.Items;
}

The effect :

enter image description here

Sample for reference : Android ListView sample Here , Xamarin Forms ListView Sample Here

Upvotes: 2

Related Questions