Android簡單實現下拉重新整理和上拉重新整理
阿新 • • 發佈:2019-01-25
先把佈局檔案裡面新增一個ListView控制元件,
用setOnScrollListener呼叫重新整理,<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context="com.xh.tx.listviewfresh.MainActivity" > <ListView android:id="@+id/listview" android:layout_width="match_parent" android:layout_height="wrap_content" > </ListView> </RelativeLayout>
實現如下圖:下拉重新整理圖:package com.xh.tx.listviewfresh; import java.util.ArrayList; import android.app.Activity; import android.os.Bundle; import android.util.Log; import android.view.Menu; import android.view.MenuItem; import android.widget.AbsListView; import android.widget.AbsListView.OnScrollListener; import android.widget.ArrayAdapter; import android.widget.ListView; public class MainActivity extends Activity { private ListView lv; private ArrayList<String> date; private ArrayAdapter adapter; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); lv = (ListView) findViewById(R.id.listview); date = new ArrayList<String>(); for (int i = 0; i < 30; i++) { date.add("測試資料" + i); } adapter = new ArrayAdapter(this, android.R.layout.simple_list_item_1, date); lv.setAdapter(adapter); lv.setOnScrollListener(new OnScrollListener() { private int firstVisibleItem, visibleItemCount, totalItemCount; @Override public void onScrollStateChanged(AbsListView view, int scrollState) { if (scrollState == OnScrollListener.SCROLL_STATE_IDLE) { if (firstVisibleItem == 0) { addTop(); } if(firstVisibleItem+visibleItemCount==totalItemCount){ adddate(); } } } @Override public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) { this.firstVisibleItem = firstVisibleItem; this.visibleItemCount = visibleItemCount; this.totalItemCount = totalItemCount; Log.i("", firstVisibleItem+"-----"+visibleItemCount+"-----"+totalItemCount); } }); } //下拉重新整理 private void addTop() { date.add(0, "上面追加資料" + (date.size() + 1)); adapter.notifyDataSetChanged(); } //上拉重新整理 private void adddate(){ date.add("下面追加資料" + (date.size() + 1)); adapter.notifyDataSetChanged(); } }
上拉重新整理圖: