Android 顶部下拉刷新添加数据&& 底部上拉刷新添加数据 ScrollListener

Android 顶部下拉刷新添加数据&& 底部上拉刷新添加数据 ScrollListener

代码如下:

</pre><pre name="code" class="java">package com.example.ListViewScroll;

import java.util.ArrayList;
import android.app.Activity;
import android.os.Bundle;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.ArrayAdapter;
import android.widget.ListView;

public class MainActivity extends Activity {
	private ArrayList<String> data;
	private ArrayAdapter adapter;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);

		ListView listview = (ListView) findViewById(R.id.list_view);
		data = new ArrayList<String>();
		for (int i = 20; i >0; i--) {
			data.add("数据" + i);
		}
		adapter = new ArrayAdapter(getApplicationContext(), android.R.layout.simple_list_item_1,data);
		listview.setAdapter(adapter);
		listview.setOnScrollListener(new OnScrollListener() {
			private int firstVisibleItem, visibleItemCount, totalItemCount;

			@Override
			public void onScrollStateChanged(AbsListView view, int scrollState) {
				
				if (scrollState == OnScrollListener.SCROLL_STATE_IDLE) {
					//判断条件为在顶部的时候下拉刷新添加一条数据
					if ((firstVisibleItem + visibleItemCount) < totalItemCount
							&& firstVisibleItem == 0) {
						addUpData();
					}
					//判断条件为在底部的时候上拉刷新添加一条数据
					if((firstVisibleItem+visibleItemCount)==totalItemCount){
						addBottomData();
					}
				}
				
			}

			@Override
			public void onScroll(AbsListView view, int firstVisibleItem,
					int visibleItemCount, int totalItemCount) {
				this.firstVisibleItem = firstVisibleItem;
				this.visibleItemCount = visibleItemCount;
				this.totalItemCount = totalItemCount;
			}
		});	
	}

	private void addUpData() {
		//ListView中添加数据,注意add方法中第一个参数0是在第一行添加
		data.add(0,"添加的数据"+data.size());
		//添加数据后适配器adapter调用notifyDataSetChanged()
		adapter.notifyDataSetChanged();
	}
	private void addBottomData() {
		//ListView中添加数据,注意add方法中第一个参数0是在第一行添加
		data.add("添加的数据"+data.size());
		//添加数据后适配器adapter调用notifyDataSetChanged()
		adapter.notifyDataSetChanged();
		
		
	}
}

布局文件
<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"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.example.ListViewScroll.MainActivity"
    android:background="@android:color/background_dark" >

    <ListView 
        android:id="@+id/list_view"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        ></ListView>

</RelativeLayout>




你可能感兴趣的:(android)