如何根据值设置网格视图项目的背景颜色

问题描述 投票:0回答:1

我想做的是根据值设置行的颜色。

最佳方法是什么?

我具有以下gridview:

<GridView
    android:id="@+id/gvContagem"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_alignParentEnd="true"
    android:layout_alignParentRight="true"
    android:numColumns="1"
    android:textStyle="bold"
    android:layout_below="@+id/headerLabel"
    android:layout_marginTop="33dp" />

和.cs文件:

        readonly JavaList<String> artigos = new JavaList<string>();

        List<string> mItems = new List<string>();

        GridView gvContagem = FindViewById<GridView>(Resource.Id.gvContagem);
        sqliteConnection con = new SqliteConnection("Data Source = " + BaseDados);

        con.Open();

        artigos.Clear();

        string stm = "SELECT Artigo, Descricao FROM Trend";

        using (SqliteCommand cmd = new SqliteCommand(stm, con))
        {
            using (SqliteDataReader rdr = cmd.ExecuteReader())
            {
                while (rdr.Read())
                {

                    artigos.Add(rdr.GetValue(0) + rdr.GetValue(1));


                }

            }

        }

ArrayAdapter<String> adapter = new ArrayAdapter<string>(this, Android.Resource.Layout.SimpleListItem1, artigos);
gvContagem.Adapter = adapter;

如果没有,我该怎么做才能复制想要的内容?

谢谢

c# xamarin xamarin.android
1个回答
0
投票

您需要定义一个自定义适配器。

创建BaseAdapter的新子类。

public class TextAdapter : BaseAdapter
{
  Context context;

  List<string> Sources;

  public TextAdapter(Context c , List<string> s)
  {
    context = c;
    Sources = s;
  }

  public override int Count
  {
     get { return Sources.Count; }
  }

  public override Java.Lang.Object GetItem(int position)
  {
     return null;
  }

  public override long GetItemId(int position)
  {
     return 0;
  }

  // create a new ImageView for each item referenced by the Adapter
  public override View GetView(int position, View convertView, ViewGroup parent)
  {
     TextView textView;

     if (convertView == null)
     {
       textView =new TextView(context);
       textView.SetLines(1);
     }
     else
     {
        textView = (TextView)convertView;
     }

     textView.SetText(Sources[position],null);

     textView.SetBackgroundColor(Android.Graphics.Color.Red); // set the color as you want 

     return textView;
  }

}

并在活动中设置适配器

gvContagem.Adapter = new TextAdapter(this,artigos);
© www.soinside.com 2019 - 2024. All rights reserved.