xListView上拉加載下拉刷新

本文章給出自定義的listview,Fragment展示數據,相應xml佈局和時間格式轉換的方法


/****************************自定義listview****************************************************/

import android.content.Context;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.LinearInterpolator;
import android.view.animation.RotateAnimation;
import android.widget.AbsListView;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.AbsListView.OnScrollListener;

public class AutoListView extends ListView implements OnScrollListener {


// 區分當前操作是刷新還是加載
public static final int REFRESH = 0;
public static final int LOAD = 1;


// 區分PULL和RELEASE的距離的大小
private static final int SPACE = 20;


// 定義header的四種狀態和當前狀態
private static final int NONE = 0;
private static final int PULL = 1;//拉
private static final int RELEASE = 2;//釋放
private static final int REFRESHING = 3;//刷新
private int state;


private LayoutInflater inflater;
private View header;
private View footer;
private TextView tip;
private TextView lastUpdate;//最後一次更新時間
private ImageView arrow;
private ProgressBar refreshing;


private TextView noData;
private TextView loadFull;
private TextView more;
private ProgressBar loading;


private RotateAnimation animation;
private RotateAnimation reverseAnimation;//反向動畫


private int startY;


private int firstVisibleItem;
private int scrollState;
private int headerContentInitialHeight;//初始高度
private int headerContentHeight;


// 只有在listview第一個item顯示的時候(listview滑到了頂部)才進行下拉刷新, 否則此時的下拉只是滑動listview
private boolean isRecorded;//記錄,說明
private boolean isLoading;// 判斷是否正在加載
private boolean loadEnable = true;// 開啓或者關閉加載更多功能
private boolean isLoadFull;//是否加載全部
private int pageSize = 10;


private OnRefreshListener onRefreshListener;
private OnLoadListener onLoadListener;


public AutoListView(Context context) {
super(context);
initView(context);
}


public AutoListView(Context context, AttributeSet attrs) {
super(context, attrs);
initView(context);
}


public AutoListView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
initView(context);
}


// 下拉刷新監聽
public void setOnRefreshListener(OnRefreshListener onRefreshListener) {
this.onRefreshListener = onRefreshListener;
}


// 加載更多監聽
public void setOnLoadListener(OnLoadListener onLoadListener) {
this.loadEnable = true;
this.onLoadListener = onLoadListener;
}


public boolean isLoadEnable() {
return loadEnable;
}


// 這裏的開啓或者關閉加載更多,並不支持動態調整
public void setLoadEnable(boolean loadEnable) {
this.loadEnable = loadEnable;
this.removeFooterView(footer);
}


public int getPageSize() {
return pageSize;
}


public void setPageSize(int pageSize) {
this.pageSize = pageSize;
}


// 初始化組件
private void initView(Context context) {


// 設置箭頭特效
animation = new RotateAnimation(0, -180,
RotateAnimation.RELATIVE_TO_SELF, 0.5f,
RotateAnimation.RELATIVE_TO_SELF, 0.5f);
//LinearInterpolator,時間插值類,其主要使用在動畫中,其作用主要是控制目標變量的變化值進行對應的變化。
animation.setInterpolator(new LinearInterpolator());
animation.setDuration(100);
animation.setFillAfter(true);


reverseAnimation = new RotateAnimation(-180, 0,
RotateAnimation.RELATIVE_TO_SELF, 0.5f,
RotateAnimation.RELATIVE_TO_SELF, 0.5f);
reverseAnimation.setInterpolator(new LinearInterpolator());
reverseAnimation.setDuration(100);
reverseAnimation.setFillAfter(true);


inflater = LayoutInflater.from(context);
footer = inflater.inflate(R.layout.listview_footer, null);
loadFull = (TextView) footer.findViewById(R.id.loadFull);
noData = (TextView) footer.findViewById(R.id.noData);
more = (TextView) footer.findViewById(R.id.more);
loading = (ProgressBar) footer.findViewById(R.id.loading);


header = inflater.inflate(R.layout.pull_to_refresh_header, null);
arrow = (ImageView) header.findViewById(R.id.arrow);
tip = (TextView) header.findViewById(R.id.tip);
lastUpdate = (TextView) header.findViewById(R.id.lastUpdate);
refreshing = (ProgressBar) header.findViewById(R.id.refreshing);


// 爲listview添加頭部和尾部,並進行初始化
headerContentInitialHeight = header.getPaddingTop();
measureView(header);
headerContentHeight = header.getMeasuredHeight();
topPadding(-headerContentHeight);
this.addHeaderView(header);
this.addFooterView(footer);
this.setOnScrollListener(this);
}


public void onRefresh() {
if (onRefreshListener != null) {
onRefreshListener.onRefresh();
}
}


public void onLoad() {
if (onLoadListener != null) {
onLoadListener.onLoad();
}
}


public void onRefreshComplete(String updateTime) {
lastUpdate.setText(this.getContext().getString(R.string.lastUpdateTime,
DateTools.getCurrentTime()));
state = NONE;
refreshHeaderViewByState();
}


// 用於下拉刷新結束後的回調
public void onRefreshComplete() {
String currentTime = DateTools.getCurrentTime();
onRefreshComplete(currentTime);
}


// 用於加載更多結束後的回調
public void onLoadComplete() {
isLoading = false;
}


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


public void onScrollStateChanged(AbsListView view, int scrollState) {
this.scrollState = scrollState;
ifNeedLoad(view, scrollState);
}


// 根據listview滑動的狀態判斷是否需要加載更多
private void ifNeedLoad(AbsListView view, int scrollState) {
if (!loadEnable) {
return;
}
try {
if (scrollState == OnScrollListener.SCROLL_STATE_IDLE
&& !isLoading
&& view.getLastVisiblePosition() == view
.getPositionForView(footer) && !isLoadFull) {
onLoad();
isLoading = true;
}
} catch (Exception e) {
}
}


/**
* 監聽觸摸事件,解讀手勢
*/
@Override
public boolean onTouchEvent(MotionEvent ev) {
switch (ev.getAction()) {
case MotionEvent.ACTION_DOWN:
if (firstVisibleItem == 0) {
isRecorded = true;
startY = (int) ev.getY();
}
break;
case MotionEvent.ACTION_CANCEL://取消
case MotionEvent.ACTION_UP:
if (state == PULL) {
state = NONE;
refreshHeaderViewByState();
} else if (state == RELEASE) {
state = REFRESHING;
refreshHeaderViewByState();
onRefresh();
}
isRecorded = false;
break;
case MotionEvent.ACTION_MOVE:
whenMove(ev);
break;
}
return super.onTouchEvent(ev);
}


// 解讀手勢,刷新header狀態
private void whenMove(MotionEvent ev) {
if (!isRecorded) {
return;
}
int tmpY = (int) ev.getY();
int space = tmpY - startY;
int topPadding = space - headerContentHeight;
switch (state) {
case NONE:
if (space > 0) {
state = PULL;
refreshHeaderViewByState();
}
break;
case PULL:
topPadding(topPadding);

//SCROLL_STATE_TOUCH_SCROLL:正在滾動
if (scrollState == SCROLL_STATE_TOUCH_SCROLL
&& space > headerContentHeight + SPACE) {
state = RELEASE;
refreshHeaderViewByState();
}
break;
case RELEASE:
topPadding(topPadding);
if (space > 0 && space < headerContentHeight + SPACE) {
state = PULL;
refreshHeaderViewByState();
} else if (space <= 0) {
state = NONE;
refreshHeaderViewByState();
}
break;
}


}


// 調整header的大小。其實調整的只是距離頂部的高度。
private void topPadding(int topPadding) {
header.setPadding(header.getPaddingLeft(), topPadding,
header.getPaddingRight(), header.getPaddingBottom());
header.invalidate();
}


/**
* 這個方法是根據結果的大小來決定footer顯示的。
* <p>
* 這裏假定每次請求的條數爲10。如果請求到了10條。則認爲還有數據。如過結果不足10條,則認爲數據已經全部加載,這時footer顯示已經全部加載
* </p>

* @param resultSize
*/
public void setResultSize(int resultSize) {
if (resultSize == 0) {
isLoadFull = true;//加載全部
loadFull.setVisibility(View.GONE);
loading.setVisibility(View.GONE);
more.setVisibility(View.GONE);
noData.setVisibility(View.VISIBLE);
} else if (resultSize > 0 && resultSize < pageSize) {
isLoadFull = true;//加載全部
loadFull.setVisibility(View.VISIBLE);
loading.setVisibility(View.GONE);
more.setVisibility(View.GONE);
noData.setVisibility(View.GONE);
} else if (resultSize == pageSize) {
isLoadFull = false;//沒有加載全部
loadFull.setVisibility(View.GONE);
loading.setVisibility(View.VISIBLE);
more.setVisibility(View.VISIBLE);
noData.setVisibility(View.GONE);
}


}


// 根據當前狀態,調整header
private void refreshHeaderViewByState() {
switch (state) {
case NONE:
topPadding(-headerContentHeight);
tip.setText(R.string.pull_to_refresh);//下拉可以刷新
refreshing.setVisibility(View.GONE);
arrow.clearAnimation();
arrow.setImageResource(R.drawable.pull_to_refresh_arrow);//向下的箭頭
break;
case PULL:
arrow.setVisibility(View.VISIBLE);
tip.setVisibility(View.VISIBLE);
lastUpdate.setVisibility(View.VISIBLE);
refreshing.setVisibility(View.GONE);//進度條
tip.setText(R.string.pull_to_refresh);
arrow.clearAnimation();
arrow.setAnimation(reverseAnimation);
break;
case RELEASE://release。釋放
arrow.setVisibility(View.VISIBLE);
tip.setVisibility(View.VISIBLE);
lastUpdate.setVisibility(View.VISIBLE);
refreshing.setVisibility(View.GONE);
tip.setText(R.string.pull_to_refresh);
tip.setText(R.string.release_to_refresh);//鬆開可以刷新
arrow.clearAnimation();
arrow.setAnimation(animation);
break;
case REFRESHING:
topPadding(headerContentInitialHeight);
refreshing.setVisibility(View.VISIBLE);
arrow.clearAnimation();
arrow.setVisibility(View.GONE);
tip.setVisibility(View.GONE);
lastUpdate.setVisibility(View.GONE);
break;
}
}


// 用來計算header大小的。比較隱晦。因爲header的初始高度就是0,貌似可以不用。
private void measureView(View child) {
ViewGroup.LayoutParams p = child.getLayoutParams();
if (p == null) {
p = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
ViewGroup.LayoutParams.WRAP_CONTENT);
}
int childWidthSpec = ViewGroup.getChildMeasureSpec(0, 0 + 0, p.width);
int lpHeight = p.height;
int childHeightSpec;
if (lpHeight > 0) {
childHeightSpec = MeasureSpec.makeMeasureSpec(lpHeight,
MeasureSpec.EXACTLY);
} else {
childHeightSpec = MeasureSpec.makeMeasureSpec(0,
MeasureSpec.UNSPECIFIED);
}
child.measure(childWidthSpec, childHeightSpec);
}


/*
* 定義下拉刷新接口
*/
public interface OnRefreshListener {
public void onRefresh();
}


/*
* 定義加載更多接口
*/
public interface OnLoadListener {
public void onLoad();
}


}

/****************************Fragment展示數據****************************************************/

public class Fragment1 extends Fragment implements OnRefreshListener,OnLoadListener{
private MyListView listView;
int a=1;
String url="http://www.oschina.net/action/api/news_list?catalog=1&&pageIndex="+a+"&&pageSize=20";
List<News> news;
MyBaseAdapter adapter;

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {

View view=inflater.inflate(R.layout.fragment, null);

listView = (MyListView) view.findViewById(R.id.listView);
//實現上拉加載
listView.setOnRefreshListener(this);
listView.setOnLoadListener(this);
listView.isLoadEnable();

//HttpUtils請求數據
HttpUtils utils=new HttpUtils();
utils.send(HttpMethod.GET, url, null,new RequestCallBack<String>() {


@Override
public void onFailure(HttpException arg0, String arg1) {

}


public void onSuccess(ResponseInfo<String> arg0) {
String result = arg0.result;
XStream stream=new XStream();
stream.processAnnotations(XMLBean1.class);
XMLBean1 bean1=(XMLBean1) stream.fromXML(result);
news = bean1.newslist.news;
adapter = new MyBaseAdapter(getActivity(), news);
listView.setAdapter(adapter);
}
});

return view;
}
/**    下拉刷新          */
public void onRefresh() {
HttpUtils utils=new HttpUtils();
utils.send(HttpMethod.GET, url, null,new RequestCallBack<String>() {


@Override
public void onFailure(HttpException arg0, String arg1) {

}


public void onSuccess(ResponseInfo<String> arg0) {
String result = arg0.result;
XStream stream=new XStream();
stream.processAnnotations(XMLBean1.class);
XMLBean1 bean1=(XMLBean1) stream.fromXML(result);
news = bean1.newslist.news;
adapter.notifyDataSetChanged();
}
});
listView.onRefreshComplete();
}
/**    上拉加載          */
public void onLoad() {
a++;
HttpUtils utils=new HttpUtils();
utils.send(HttpMethod.GET, url, null,new RequestCallBack<String>() {


@Override
public void onFailure(HttpException arg0, String arg1) {

}


public void onSuccess(ResponseInfo<String> arg0) {
String result = arg0.result;
XStream stream=new XStream();
stream.processAnnotations(XMLBean1.class);
XMLBean1 bean1=(XMLBean1) stream.fromXML(result);
List<News> news2 = bean1.newslist.news;
news.addAll(news2);//追加數據
adapter.notifyDataSetChanged();
listView.onLoadComplete();
}
});
}
}

/****************************工具類,轉換時間****************************************************/

public class DateTools {
/*
* 將時間戳轉爲字符串 ,格式:yyyy.MM.dd  星期幾
*/
@SuppressWarnings("null")
public static String getSection(String cc_time) {
String re_StrTime = null;
SimpleDateFormat sdf = new SimpleDateFormat("yyyy.MM.dd  EEEE");
//對於創建SimpleDateFormat傳入的參數:EEEE代表星期,如“星期四”;MMMM代表中文月份,如“十一月”;MM代表月份,如“11”;
//yyyy代表年份,如“2010”;dd代表天,如“25”
// 例如:cc_time=1291778220
if(cc_time!=null || !cc_time.equals("")){
long lcc_time = Long.valueOf(cc_time);
re_StrTime = sdf.format(new Date(lcc_time * 1000L));
}

return re_StrTime;
}
/*
* 將系統時間轉爲字符串 ,格式:yyyy-MM-dd  HH:mm:ss
*/

public static String getCurrentTime(String format) {
Date date = new Date();
SimpleDateFormat sdf = new SimpleDateFormat(format, Locale.getDefault());
String currentTime = sdf.format(date);
return currentTime;
}


public static String getCurrentTime() {
return getCurrentTime("yyyy-MM-dd  HH:mm:ss");
}
}

/*
* listView的footer
*/

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:gravity="center"
    android:orientation="horizontal" >


    <TextView
        android:id="@+id/loadFull"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:gravity="center"
        android:padding="5dp"
        android:text="@string/load_full"
        android:visibility="gone" />


    <TextView
        android:id="@+id/noData"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:gravity="center"
        android:padding="5dp"
        android:text="@string/no_data"
        android:visibility="gone" />


    <TextView
        android:id="@+id/more"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:gravity="center"
        android:padding="5dp"
        android:text="@string/more" />


    <ProgressBar
        android:id="@+id/loading"
        style="@style/customProgressBar" />


</LinearLayout>

/*
* listView的header的xml
*/

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:gravity="center"
    android:orientation="vertical" >


    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:paddingBottom="10dp" >


        <LinearLayout
            android:id="@+id/layout"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_centerHorizontal="true"
            android:layout_centerVertical="true"
            android:orientation="vertical" >


            <ProgressBar
                android:id="@+id/refreshing"
                style="@style/customProgressBar" />


            <TextView
                android:id="@+id/tip"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_gravity="center" />


            <TextView
                android:id="@+id/lastUpdate"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_gravity="center"
                android:textSize="12sp" />
        </LinearLayout>


        <ImageView
            android:id="@+id/arrow"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_centerVertical="true"
            android:layout_marginRight="20dp"
            android:layout_toLeftOf="@id/layout"
            android:contentDescription="@string/d"
            android:src="@drawable/pull_to_refresh_arrow" />
    </RelativeLayout>


    <ImageView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="@drawable/h_line"
        android:contentDescription="@string/d" />


</LinearLayout>


 <!--String 自定義組件 -->
    <string name="pull_to_refresh">下拉可以刷新</string>
    <string name="release_to_refresh">鬆開可以刷新</string>
    <string name="lastUpdateTime">最近更新:%s</string>
    <string name="load_full">已加載全部</string>
    <string name="no_data">暫無數據</string>
    <string name="more">加載中</string>
     <!-- 消除警告,可忽略 -->
    <string name="d">圖片描述</string>


 <!-- Style -->

<style name="customProgressBar" parent="@android:style/Widget.ProgressBar.Small">
        <item name="android:indeterminateDrawable">@drawable/custom_progress_bar</item>
        <item name="android:layout_width">21dip</item>
        <item name="android:layout_height">21dip</item>
        <item name="android:layout_gravity">center</item>
    </style>


 <!--custom_progress_bar.xml -->

<animation-list xmlns:android="http://schemas.android.com/apk/res/android"
    android:oneshot="false" >


    <item
        android:drawable="@drawable/loading_0"
        android:duration="100"/>
    <item
        android:drawable="@drawable/loading_1"
        android:duration="100"/>
    <item
        android:drawable="@drawable/loading_2"
        android:duration="100"/>
    <item
        android:drawable="@drawable/loading_3"
        android:duration="100"/>
    <item
        android:drawable="@drawable/loading_4"
        android:duration="100"/>
    <item
        android:drawable="@drawable/loading_5"
        android:duration="100"/>
    <item
        android:drawable="@drawable/loading_6"
        android:duration="100"/>
    <item
        android:drawable="@drawable/loading_7"
        android:duration="100"/>


</animation-list>


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章