我使用自定义适配器从列表中填充的 gridView 遇到了一个奇怪的问题。
一切看起来都很正常,直到 gridView 的第一页已满,然后一些后续项目丢失或不同步。
我做了两个屏幕截图,第一个是单列,第二个是两个。如您所见,第一页都正确呈现,如下图所示:
单栏:http ://screencast.com/t/mSoEsDf1cY
和
两栏:http ://screencast.com/t/i6zfPLYf
我简化了代码来演示这个问题:
public class Activity1 : Activity
{
List<Item> _items = null;
protected override void OnCreate (Bundle bundle)
{
base.OnCreate (bundle);
// Set our view from the "main" layout resource
SetContentView (Resource.Layout.Main);
_items = new List<Item>();
for ( int i =0; i < 30; i++)
{
Item newItem = new Item();
newItem.Text = "Item " + i;
newItem.Bitmap = Android.Graphics.BitmapFactory.DecodeResource( this.Resources, Resource.Drawable.Icon );
_items.Add( newItem );
}
GridView grid = FindViewById<GridView> (Resource.Id.gridView1);
grid.SetNumColumns(2);
ItemGridViewAdapter adapter = new ItemGridViewAdapter( this, _items);
grid.Adapter = adapter;
}
}
public class Item
{
public Android.Graphics.Bitmap Bitmap { get; set; }
public string Text { get; set; }
}
public class ItemGridViewAdapter : BaseAdapter<Item>
{
private List<Item> _items = null;
private Context _context = null;
public override int Count {
get {
return _items.Count;
}
}
public override long GetItemId (int position)
{
return position;
}
public override Item this[int position] {
get {
return _items[position];
}
}
public ItemGridViewAdapter (Context context, List<Item> items)
{
_items = items;
_context = context;
}
public override View GetView (int position, View convertView, ViewGroup parent)
{
//based on http://developer.android.com/guide/topics/ui/layout/gridview.html
RelativeLayout layout = null;
if (convertView == null) {
layout = new RelativeLayout( _context );
RelativeLayout.LayoutParams rlp = new RelativeLayout.LayoutParams (RelativeLayout.LayoutParams.WrapContent, RelativeLayout.LayoutParams.WrapContent);
ImageView image = new ImageView (_context);
image.LayoutParameters = new Gallery.LayoutParams (150, 150);
image.SetImageBitmap ( this[position].Bitmap );
image.Id = 1;
layout.AddView (image);
RelativeLayout.LayoutParams title_lp = new RelativeLayout.LayoutParams (RelativeLayout.LayoutParams.WrapContent, RelativeLayout.LayoutParams.WrapContent);
TextView title = new TextView (_context);
title.Text = this[position].Text;
title.Id = 2;
title.SetTextColor (Android.Graphics.Color.White);
title_lp.AddRule (LayoutRules.RightOf, 1);
title_lp.AddRule (LayoutRules.CenterVertical);
layout.AddView (title, title_lp);
} else {
layout = (RelativeLayout)convertView;
}
return layout;
}
}
任何想法将不胜感激。