今天项目经理找我说Listview加载更多的时候会出现一些问题,主要表现在会顿一下。让我我就去找Java的方法看看。自己写出了mono 的加载更多功能。和大家分享一下
先看效果
首先是模型类ListItem
public class ListItem { public string item{ get;set;} }
然后是数据适配器类
//数据适配器类 public class ListViewAdapter:ArrayAdapter<ListItem> { public ListViewAdapter(Context context): base(context, 0) { } public override View GetView(int position, View convertView, ViewGroup parent) { View view; if (convertView !=null) { view = convertView; } else { view = LayoutInflater.From(this.Context).Inflate(Resource.Layout.listItem, null); } TextView tv = view.FindViewById<TextView>(Resource.Id.Itemstring); ListItem it = GetItem(position); tv.Text = it.item; return view; } }
最后是创建主界面
public class Activity1 : Activity { public ListView listview; public int visibleLastIndex = 0; //最后的可视项索引 public int visibleItemCount; // 当前窗口可见项总数 public View loadMoreView; //更多视图 public ListViewAdapter adapter; //数据适配器 private Handler handler = new Handler(); List<ListItem> items = new List<ListItem>(); protected override void OnCreate(Bundle bundle) { base.OnCreate(bundle); // Set our view from the "main" layout resource SetContentView(Resource.Layout.Main); //在listview 后面加载更多是视图 loadMoreView = LayoutInflater.Inflate(Resource.Layout.Main,null); listview = FindViewById<ListView>(Resource.Id.listview); adapter = new ListViewAdapter(this); //初始化 initAdapter(); listview.Adapter = adapter; listview.ScrollStateChanged += new EventHandler<AbsListView.ScrollStateChangedEventArgs>(listview_ScrollStateChanged); //loadMoreButton.Click += new EventHandler(loadMoreButton_Click); //在原有Listview的后面加上加载来的数据数据 listview.AddFooterView(loadMoreView); } // void loadMoreClick() { //开启java 多线程加载更多 //开启委托 Action ac = new Action(getMore); //runnable 只提供这一种构造方法…… handler.PostDelayed(new Runnable(ac){}, 1000); } //加载更多初始化方法 void getMore() { LoadData(); adapter.NotifyDataSetChanged();//数据集变化后,通知adapter listview.SetSelection(visibleLastIndex - visibleItemCount + 1);//设置选中项 } //加载更多获取数据方法 void LoadData() { int count = adapter.Count; for (int i = 0; i < count+12; i++) { ListItem item = new ListItem(); item.item = i + "呵呵"+ i; items.Add(item); adapter.Add(item); } } //滚动状态改变是发生 void listview_ScrollStateChanged(object sender, AbsListView.ScrollStateChangedEventArgs e) { ListView lv = sender as ListView; this.visibleItemCount = lv.LastVisiblePosition - lv.FirstVisiblePosition;//当前窗口可见项总数 visibleLastIndex = lv.LastVisiblePosition+1; //最后可视索引 int itemsLastIndex = adapter.Count-1; //数据集最后一项的索引 int lastIndex = itemsLastIndex +1; //加上底部的loadMoreView项 if (ScrollState.Idle == e.ScrollState && visibleLastIndex == lastIndex) { //如果自动加载,可以异步加载 loadMoreClick(); } } //初始化适配器 private void initAdapter() { for (int i = 0; i < 15; i++) { ListItem item = new ListItem(); item.item = i+"哈哈哈"+i; items.Add(item); adapter.Add(item); } } }
其实就是在Listview滚动到底部是触发加载事件,加载事件向adapter 里面写入数据,adapter 状态改变的时候就会触发向Listview底部加数据的一个过程
这种实现方法很流畅。在项目中经常会用到