如何在RecyclerView Xamarin Android中更改TextView的背景颜色

时间:2019-02-06 14:52:43

标签: android xamarin

基本上,这是一个recyclerview,我填充了一些textviews以显示某些类别。我可以访问recyclerview中单击的项目的位置,但是如何获得对实际textview的引用来设置背景颜色?

这是我的代码

cd path/to/models/research/
protoc object_detection/protos/*.proto --python_out=.

1 个答案:

答案 0 :(得分:0)

我找到了问题的答案,以防万一。您可以使用RecyclerView.Adapter的OnBindViewHolder方法并创建所有textview的引用列表。然后使用该位置使它被点击。

 // ADAPTER

// Adapter to connect the data set to the RecyclerView: 
public class CategoriesAdapter : RecyclerView.Adapter
{
    // Event handler for item clicks:
    public event EventHandler<int> ItemClick;

    // Underlying data set 
    public List<Category> Categories;

  public List<TextView> TextViews = new List<TextView>();

    // Load the adapter with the data set at construction time:
    public CategoriesAdapter(List<Category> categories)
    {
        this.Categories = categories;
    }

    // Create a new  CardView (invoked by the layout manager): 
    public override RecyclerView.ViewHolder  OnCreateViewHolder(ViewGroup parent, int viewType)
    {
        // Inflate the CardView for the photo:
        View itemView = LayoutInflater.From(parent.Context).
            Inflate(Resource.Layout.CategoryTextView, parent, false);

        // Create a ViewHolder to find and hold these view references, and 
        // register OnClick with the view holder:
        CategoryViewHolder vh = new CategoryViewHolder(itemView, OnClick);


        return vh;
    }

    // Fill in the contents (invoked by the layout manager):
    public override void  OnBindViewHolder(RecyclerView.ViewHolder holder, int position)
    {
        var vh = holder as CategoryViewHolder;



        vh.CategoryTextView.Text = Categories[position].Name;

        TextViews.Add(vh.CategoryTextView);



        if (position == 0)
        {
            vh.CategoryTextView.SetBackgroundColor(Color.Aqua); 
        }


        vh.CategoryTextView.Click += (sender, e) =>
        {

            foreach (var textView in TextViews)
            {
                textView.SetBackgroundColor(Color.White);
            }

            ((TextView)sender).SetBackgroundColor(Color.Aqua);



        };

    }

    // Return the number of photos available in the photo album:
    public override int ItemCount
    {
        get { return Categories.Count; }
    }

    // Raise an event when the item-click takes place:
    void OnClick(int position)
    {
        if (ItemClick != null)
            ItemClick(this, position);
    }
}