在我的应用程序中的简单ListView中,我想在向下滚动时添加列表末尾的项目并刷新它。我的代码只能将数据传递到ListView,它无法添加到列表的末尾并刷新它。请帮我解决这个问题。感谢。
private ItemAdapter adapter;
public class ReceivedFragment extends ListFragment implements AbsListView.OnScrollListener {
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
items = new ArrayList<Item>();
for ( int i=0; i<=10; i++){
String a = String.format("title %s", i);
String b = String.format("description %s", i);
Item item = new Item(a , b , String.valueOf(i) );
items.add(item);
}
adapter = new ItemAdapter(getActivity(), items);
setListAdapter(adapter);
return super.onCreateView(inflater, container, savedInstanceState);
}
@Override
public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
if (prevVisibleItem != firstVisibleItem) {
if ((firstVisibleItem + visibleItemCount) == totalItemCount) {
Toast.makeText(getActivity(), R.string.please_wait_to_response_from_server, Toast.LENGTH_LONG).show();
Thread thread = new Thread() {
@Override
public void run() {
getActivity().runOnUiThread(new Runnable() {
public void run() {
for (int i = (int) getLastID(); i <= getLastID() + 10; i++) {
String a = String.format("title %s", i);
String b = String.format("description %s", i);
Item item = new Item(a, b, String.valueOf(i));
items.add(item);
}
adapter.notifyDataSetChanged();
}
});
}
};
}
}
}
@Override
public void onListItemClick(ListView l, View v, int position, long thisID) {
super.onListItemClick(l, v, position, thisID);
}
public long getLastID() {
return Long.parseLong(items.get(items.size() - 1).getmLastID());
}
}
ArrayAdapter:
public class ItemAdapter extends ArrayAdapter<Item> {
public ItemAdapter(Context c, List<Item> items) {
super(c,0,items);
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
ItemView itemView = (ItemView)convertView;
if (null == itemView)
itemView = ItemView.inflate(parent);
itemView.setItem(getItem(position));
itemView.setBackgroundColor(((position % 2)!=0) ? Color.rgb(229, 229, 229) : Color.WHITE);
return itemView;
}
}
答案 0 :(得分:1)
ArrayAdapter adapter = (ArrayAdapter)yourListView.getAdapter();
ArrayList<Item> items = new ArrayList<Item>();
for ( int i= (int) getLastID(); i<= getLastID() + 10; i++){
String a = String.format("title %s", i);
String b = String.format("description %s", i);
Item item = new Item(a , b , String.valueOf(i) );
items.add(item);
}
adapter.addAll(items);
adapter.notifyDataSetChanged();
答案 1 :(得分:-1)
要使用新行加载ListView
,您应在列表更改后致电setAdapter
。
而不是:
new ItemAdapter(getActivity(), items).notifyDataSetChanged();
我会尝试
my_listview.setAdapter(new ItemAdapter(getActivity(), items); //items must contains the old and the new items
或者只是
setAdapter(new ItemAdapter(getActivity(), items);
当您使用ListFragment时。您可能还需要拨打notifyDataSetChanged()
,但我不完全确定