2017-05-05 33 views
0

我有一个显示客户端名称和年龄的简单列表视图。该列表需要滚动,我做了行的背景替代颜色(白色和蓝色)。但是,如果包含客户年龄的单元格为18,我想用橙色突出显示,如果年龄为负值(表示出现错误),我想用红色突出显示。 它一切正常,直到我开始滚动。在这一点上,一切都搞砸了,橙色/红色背景没有正确应用。 适配器代码如下。在调试过程中,我注意到变量的位置在每次迭代中都会改变值。例如,如果我最初显示只有8行,滚动后,我看到该位置去9,10 ...然后5,4 ...我明白这可能是因为它重复使用行,但我怎样才能使其按预期工作?我希望有人能够帮助,因为我尝试了很多次,但仍然没有成功。谢谢。Xamarin在单元格被重用时在列表视图中突出显示单元格

class MyListViewAdapter : BaseAdapter<dbClient> 
{ 
    public List<dbClient> mItems; 
    private Context mContext; 
    private int mRowLayout; 
    private string[] mAlternatingColors; 

    // Default constructor 
    public MyListViewAdapter(Context context, List<dbClient> items, int rowLayout) 
    { 
     mItems = items; 
     mContext = context; 
     mRowLayout = rowLayout; 
     mAlternatingColors = new string[] { "#F2F2F2", "#00bfff" }; 
    } 

    // Tells how many rows are in the dataset 
    public override int Count 
    { 
     get { return mItems.Count; } 
    } 

    // Return a row identifier 
    public override long GetItemId(int position) 
    { 
     return position; 
    } 

    // Return the data associated with a particular row 
    public override dbClient this[int position] 
    { 
     get { return mItems[position]; } 
    } 

    // Return a view for each row 
    public override View GetView(int position, View convertView, ViewGroup parent) 
    { 
     View row = convertView; 
     if(row == null) 
     { 
      row = LayoutInflater.From(mContext).Inflate(Resource.Layout.listview_row, null, false); 
     } 

     row.SetBackgroundColor(Color.ParseColor(mAlternatingColors[position % mAlternatingColors.Length])); 

     TextView txtName = row.FindViewById<TextView>(Resource.Id.nameView); 
     txtName.Text = mItems[position].Name; 

     TextView txtAge = row.FindViewById<TextView>(Resource.Id.ageView); 
     txtAge.Text = mItems[position].Age.ToString(); 

     // highlight if aged 18 
     if(txtAge.Text == "18") 
     { txtAge.SetBackgroundColor(Color.Orange); } 
     // signale there is error in the age reported 
     if(txtAge.Text.Contains("-")) 
     { txtAge.SetBackgroundColor(Color.Red); } 



     return row; 
    } 

    private Color GetColorFromInteger(int color) 
    { 
     return Color.Rgb(Color.GetRedComponent(color), Color.GetGreenComponent(color), Color.GetBlueComponent(color)); 
    } 
} 
+0

你检查我的答案?任何问题? –

回答

0

,直到我开始滚动这一切工作正常。在这一点上,一切都搞砸了,橙色/红色背景没有正确应用。

你是正确的,它重用行,所以在你的代码,你变了颜色不同的原因,你没有改回原来的颜色。只需要改变你的代码的一部分,GetView例如像这样:

// highlight if aged 18 
if (txtAge.Text == "18") 
{ txtAge.SetBackgroundColor(Color.Orange); } 
// signale there is error in the age reported 
else if (txtAge.Text.Contains("-")) 
{ txtAge.SetBackgroundColor(Color.Red); } 
// set back to default color 
else 
{ 
    txtAge.SetBackgroundColor(Color.Black); 
} 
相关问题