簡體   English   中英

如何根據值設置 gridview 項目的背景顏色

[英]How to set background color of gridview item based on value

我想要做的是,根據值,設置行的顏色。

最好的方法是什么?

我有以下 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;

如果沒有,我該怎么做才能復制我想要的?

謝謝

您需要定義一個自定義適配器。

創建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;
  }

}

並在Activity中設置Adapter

gvContagem.Adapter = new TextAdapter(this,artigos);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM