2017-05-05 32 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); 
} 
相關問題