XListView的上拉加载和下拉刷新

来源:互联网 发布:信用卡网络推广合作 编辑:程序博客网 时间:2024/05/18 07:18

第一种方法 依赖架包(如图所示就可以使用XListView)

maven{url'https://jitpack.io'}

compile 'com.github.ForgiveAll:Xlistview:v1.0'




//第二种方法

第一步布局

xlistview_footer.xml的布局

<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"    android:layout_width="fill_parent"    android:layout_height="wrap_content" >    <RelativeLayout        android:id="@+id/xlistview_footer_content"        android:layout_width="fill_parent"        android:layout_height="wrap_content"        android:padding="10dp" >        <ProgressBar            android:id="@+id/xlistview_footer_progressbar"            android:layout_width="wrap_content"            android:layout_height="wrap_content"            android:layout_centerInParent="true"            android:visibility="invisible" />        <TextView            android:id="@+id/xlistview_footer_hint_textview"            android:layout_width="wrap_content"            android:layout_height="wrap_content"            android:layout_centerInParent="true"            android:text="@string/xlistview_footer_hint_normal" />    </RelativeLayout></LinearLayout>

xlistview_header.xml的布局

<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"    android:layout_width="fill_parent"    android:layout_height="wrap_content"    android:gravity="bottom" >    <RelativeLayout        android:id="@+id/xlistview_header_content"        android:layout_width="fill_parent"        android:layout_height="60dp" >        <LinearLayout            android:id="@+id/xlistview_header_text"            android:layout_width="wrap_content"            android:layout_height="wrap_content"            android:layout_centerInParent="true"            android:gravity="center"            android:orientation="vertical" >            <TextView                android:id="@+id/xlistview_header_hint_textview"                android:layout_width="wrap_content"                android:layout_height="wrap_content"                android:text="@string/xlistview_header_hint_normal" />            <LinearLayout                android:layout_width="wrap_content"                android:layout_height="wrap_content"                android:layout_marginTop="3dp" >                <TextView                    android:layout_width="wrap_content"                    android:layout_height="wrap_content"                    android:text="@string/xlistview_header_last_time"                    android:textSize="12sp" />                <TextView                    android:id="@+id/xlistview_header_time"                    android:layout_width="wrap_content"                    android:layout_height="wrap_content"                    android:textSize="12sp" />            </LinearLayout>        </LinearLayout>        <ImageView            android:id="@+id/xlistview_header_arrow"            android:layout_width="wrap_content"            android:layout_height="wrap_content"            android:layout_alignLeft="@id/xlistview_header_text"            android:layout_centerVertical="true"            android:layout_marginLeft="-35dp"            android:src="@drawable/xlistview_arrow" />        <ProgressBar            android:id="@+id/xlistview_header_progressbar"            android:layout_width="30dp"            android:layout_height="30dp"            android:layout_alignLeft="@id/xlistview_header_text"            android:layout_centerVertical="true"            android:layout_marginLeft="-40dp"            android:visibility="invisible" />    </RelativeLayout></LinearLayout>

第二步在values的文件夹下

color.xml

<?xml version="1.0" encoding="utf-8"?><resources>    <color name="transparent">#00000000</color>    <color name="yellow">#ffcc00</color>    <color name="yellow_back">#FFEDBB</color>    <color name="yellow_test">#A25B00</color>    <color name="white">#ffffff</color>    <color name="black">#cc000000</color>    <color name="news_list_black">#333333</color>    <color name="news_list_time">#969696</color>    <color name="news_test">#5e5e5e</color>    <color name="third_color">#C9C9C9</color>    <color name="blue">#0000ff</color>    <color name="red">#ff0000</color>    <color name="light_red">#ff3300</color>    <color name="green">#04c004</color>    <color name="choice_house_press">#86d3ef</color>    <color name="gold">#ffd700</color>    <color name="orange">#ffa500</color>    <color name="brown">#a52a2a</color>    <color name="deepskyblue">#00bfff</color>    <color name="darkblue">#00008b</color>    <color name="gray">#ffe7e7e7</color>    <color name="light_gray">#EFEFEF</color>    <color name="light_lanse">#33ffff</color>    <!-- 深灰色 -->    <color name="gray1">#5c615d</color>    <!-- 灰色 -->    <color name="gray2">#949393</color>    <!-- 淡灰色 -->    <color name="gray3">#CCCCCC</color>    <!-- 淡淡灰色 -->    <color name="gray4">#e5e5e5</color>    <color name="bg_app">#efefef</color>    <color name="bg_actionbar">#52c83b</color>    <color name="actionbar_selected">#298a24</color>    <color name="item_checked">#202020</color>    <color name="item_text_checked">#d4bc7c</color>    <color name="list_divider">#595959</color>    <color name="bg_left_tabs">#3d3d3d</color>    <color name="dialog_title_divider">#efefef</color>    <color name="text_default">#B4B4B4</color>    <color name="light_yellow">#fffae2</color>    <color name="more_footer_text_color">#33cccc</color>    <color name="more_footer_text_color1">#f3f3f3</color></resources>

dimens.xml

<resources>    <!-- Default screen margins, per the Android Design guidelines. -->    <dimen name="activity_horizontal_margin">16dp</dimen>    <dimen name="activity_vertical_margin">16dp</dimen></resources>

strings.xml

<?xml version="1.0" encoding="utf-8"?><resources>    <string name="app_name">listviewshangxia</string>    <string name="hello_world">Hello world!</string>    <string name="action_settings">Settings</string>  <!-- 下拉刷新,上拉加载更多 -->    <string name="xlistview_header_hint_normal">下拉刷新</string>    <string name="xlistview_header_hint_ready">松开刷新数据</string>    <string name="xlistview_header_hint_loading">正在加载...</string>    <string name="xlistview_header_last_time">上次更新时间:</string>    <string name="xlistview_footer_hint_normal">查看更多</string>    <string name="xlistview_footer_hint_ready">松开载入更多</string></resources>

sytle.xml

<resources>    <!--        Base application theme, dependent on API level. This theme is replaced        by AppBaseTheme from res/values-vXX/styles.xml on newer devices.    -->    <style name="AppBaseTheme" parent="android:Theme.Light">        <!--            Theme customizations available in newer API levels can go in            res/values-vXX/styles.xml, while customizations related to            backward-compatibility can go here.        -->    </style>    <!-- Application theme. -->    <style name="AppTheme" parent="AppBaseTheme">        <!-- All customizations that are NOT specific to a particular API-level can go here. -->    </style></resources>


XListView.java

package com.example.listviewshangxia;import java.text.SimpleDateFormat;import java.util.Date;import android.annotation.SuppressLint;import android.content.Context;import android.util.AttributeSet;import android.view.MotionEvent;import android.view.View;import android.view.ViewTreeObserver.OnGlobalLayoutListener;import android.view.animation.DecelerateInterpolator;import android.widget.AbsListView;import android.widget.AbsListView.OnScrollListener;import android.widget.ListAdapter;import android.widget.ListView;import android.widget.RelativeLayout;import android.widget.Scroller;import android.widget.TextView;public class XListView extends ListView implements OnScrollListener {private float mLastY = -1; // save event yprivate Scroller mScroller; // 用于回滚private OnScrollListener mScrollListener; // 回滚监听// 触发刷新和加载更多接口.private IXListViewListener mListViewListener;// -- 头部的Viewprivate XListViewHeader mHeaderView;// 查看头部的内容,用它计算头部高度,和隐藏它// 当禁用的时候刷新private RelativeLayout mHeaderViewContent;private TextView mHeaderTimeView;private int mHeaderViewHeight; // 头部View的高private boolean mEnablePullRefresh = true;private boolean mPullRefreshing = false; // 是否刷新.// -- 底部的Viewprivate XListViewFooter mFooterView;private boolean mEnablePullLoad;private boolean mPullLoading;private boolean mIsFooterReady = false;// 总列表项,用于检测列表视图的底部private int mTotalItemCount;// for mScroller, 滚动页眉或者页脚private int mScrollBack;private final static int SCROLLBACK_HEADER = 0;// 顶部private final static int SCROLLBACK_FOOTER = 1;// 下部private final static int SCROLL_DURATION = 400; // 滚动回时间private final static int PULL_LOAD_MORE_DELTA = 50; // 当大于50PX的时候,加载更多private final static float OFFSET_RADIO = 1.8f; // support iOS like pull// feature./** * @param context */public XListView(Context context) {super(context);initWithContext(context);}public XListView(Context context, AttributeSet attrs) {super(context, attrs);initWithContext(context);}public XListView(Context context, AttributeSet attrs, int defStyle) {super(context, attrs, defStyle);initWithContext(context);}private void initWithContext(Context context) {mScroller = new Scroller(context, new DecelerateInterpolator());// XListView need the scroll event, and it will dispatch the event to// user's listener (as a proxy).super.setOnScrollListener(this);// 初始化头部ViewmHeaderView = new XListViewHeader(context);mHeaderViewContent = (RelativeLayout) mHeaderView.findViewById(R.id.xlistview_header_content);mHeaderTimeView = (TextView) mHeaderView.findViewById(R.id.xlistview_header_time);addHeaderView(mHeaderView);// 把头部这个视图添加进去// 初始化底部的ViewmFooterView = new XListViewFooter(context);// 初始化头部高度mHeaderView.getViewTreeObserver().addOnGlobalLayoutListener(new OnGlobalLayoutListener() {@Overridepublic void onGlobalLayout() {mHeaderViewHeight = mHeaderViewContent.getHeight();getViewTreeObserver().removeGlobalOnLayoutListener(this);}});}@Overridepublic void setAdapter(ListAdapter adapter) {// 确定XListViewFooter是最后底部的View, 并且只有一次if (mIsFooterReady == false) {mIsFooterReady = true;addFooterView(mFooterView);}super.setAdapter(adapter);}/** * 启用或禁用下拉刷新功能. *  * @param enable */public void setPullRefreshEnable(boolean enable) {mEnablePullRefresh = enable;if (!mEnablePullRefresh) { // 禁用,隐藏内容mHeaderViewContent.setVisibility(View.INVISIBLE);// 如果为false则隐藏下拉刷新功能} else {mHeaderViewContent.setVisibility(View.VISIBLE);// 否则就显示下拉刷新功能}}/** * 启用或禁用加载更多的功能. *  * @param enable */public void setPullLoadEnable(boolean enable) {mEnablePullLoad = enable;if (!mEnablePullLoad) {mFooterView.hide();// 隐藏mFooterView.setOnClickListener(null);} else {mPullLoading = false;mFooterView.show();// 显示mFooterView.setState(XListViewFooter.STATE_NORMAL);// both "上拉" 和 "点击" 将调用加载更多.mFooterView.setOnClickListener(new OnClickListener() {@Overridepublic void onClick(View v) {startLoadMore();}});}}/** * 停止刷新, 重置头视图. */public void stopRefresh() {if (mPullRefreshing == true) {mPullRefreshing = false;resetHeaderHeight();}}/** * stop load more, reset footer view. */public void stopLoadMore() {if (mPullLoading == true) {mPullLoading = false;mFooterView.setState(XListViewFooter.STATE_NORMAL);}}/** * 設置最後一次刷新時間 *  * @param time */@SuppressLint("SimpleDateFormat")public void setRefreshTime(String time) { SimpleDateFormat   formatter   =   new   SimpleDateFormat   ("yyyy年MM月dd日   HH:mm:ss     ");     Date   curDate   =   new   Date(System.currentTimeMillis()); //获取当前时间    String   str   =   formatter.format(curDate);  mHeaderTimeView.setText(str);}private void invokeOnScrolling() {if (mScrollListener instanceof OnXScrollListener) {OnXScrollListener l = (OnXScrollListener) mScrollListener;l.onXScrolling(this);}}private void updateHeaderHeight(float delta) {mHeaderView.setVisiableHeight((int) delta+ mHeaderView.getVisiableHeight());if (mEnablePullRefresh && !mPullRefreshing) { // 未处于刷新状态,更新箭头if (mHeaderView.getVisiableHeight() > mHeaderViewHeight) {mHeaderView.setState(XListViewHeader.STATE_READY);} else {mHeaderView.setState(XListViewHeader.STATE_NORMAL);}}setSelection(0); // scroll to top each time}/** * 重置头视图的高度 */private void resetHeaderHeight() {int height = mHeaderView.getVisiableHeight();if (height == 0) // 不显示.return;// 不显示刷新和标题的时候,什么都不显示if (mPullRefreshing && height <= mHeaderViewHeight) {return;}int finalHeight = 0; // 默认:滚动回头.// 当滚动回显示所有头标题时候,刷新if (mPullRefreshing && height > mHeaderViewHeight) {finalHeight = mHeaderViewHeight;}mScrollBack = SCROLLBACK_HEADER;mScroller.startScroll(0, height, 0, finalHeight - height,SCROLL_DURATION);// 触发刷新invalidate();}// 改变底部视图高度private void updateFooterHeight(float delta) {int height = mFooterView.getBottomMargin() + (int) delta;if (mEnablePullLoad && !mPullLoading) {if (height > PULL_LOAD_MORE_DELTA) { // 高度足以调用加载更多mFooterView.setState(XListViewFooter.STATE_READY);} else {mFooterView.setState(XListViewFooter.STATE_NORMAL);}}mFooterView.setBottomMargin(height);// setSelection(mTotalItemCount - 1); // scroll to bottom}private void resetFooterHeight() {int bottomMargin = mFooterView.getBottomMargin();if (bottomMargin > 0) {mScrollBack = SCROLLBACK_FOOTER;mScroller.startScroll(0, bottomMargin, 0, -bottomMargin,SCROLL_DURATION);invalidate();}}// 开始加载更多private void startLoadMore() {mPullLoading = true;mFooterView.setState(XListViewFooter.STATE_LOADING);if (mListViewListener != null) {mListViewListener.onLoadMore();}}// 触发事件@Overridepublic boolean onTouchEvent(MotionEvent ev) {if (mLastY == -1) {mLastY = ev.getRawY();}switch (ev.getAction()) {case MotionEvent.ACTION_DOWN:mLastY = ev.getRawY();break;case MotionEvent.ACTION_MOVE:final float deltaY = ev.getRawY() - mLastY;mLastY = ev.getRawY();System.out.println("数据监测:" + getFirstVisiblePosition() + "---->"+ getLastVisiblePosition());if (getFirstVisiblePosition() == 0&& (mHeaderView.getVisiableHeight() > 0 || deltaY > 0)) {// 第一项显示,标题显示或拉下来.updateHeaderHeight(deltaY / OFFSET_RADIO);invokeOnScrolling();} else if (getLastVisiblePosition() == mTotalItemCount - 1&& (mFooterView.getBottomMargin() > 0 || deltaY < 0)) {// 最后一页,已停止或者想拉起updateFooterHeight(-deltaY / OFFSET_RADIO);}break;default:mLastY = -1; // 重置if (getFirstVisiblePosition() == 0) {// 调用刷新,如果头部视图高度大于设定高度。if (mEnablePullRefresh&& mHeaderView.getVisiableHeight() > mHeaderViewHeight) {mPullRefreshing = true;// 那么刷新mHeaderView.setState(XListViewHeader.STATE_REFRESHING);if (mListViewListener != null) {mListViewListener.onRefresh();}}resetHeaderHeight();// 刷新完毕,重置头部高度,也就是返回上不}if (getLastVisiblePosition() == mTotalItemCount - 1) {// 调用加载更多.if (mEnablePullLoad&& mFooterView.getBottomMargin() > PULL_LOAD_MORE_DELTA) {startLoadMore();// 如果底部视图高度大于可以加载高度,那么就开始加载}resetFooterHeight();// 重置加载更多视图高度}break;}return super.onTouchEvent(ev);}@Overridepublic void computeScroll() {if (mScroller.computeScrollOffset()) {if (mScrollBack == SCROLLBACK_HEADER) {mHeaderView.setVisiableHeight(mScroller.getCurrY());} else {mFooterView.setBottomMargin(mScroller.getCurrY());}postInvalidate();invokeOnScrolling();}super.computeScroll();}@Overridepublic void setOnScrollListener(OnScrollListener l) {mScrollListener = l;}@Overridepublic void onScrollStateChanged(AbsListView view, int scrollState) {if (mScrollListener != null) {mScrollListener.onScrollStateChanged(view, scrollState);}}@Overridepublic void onScroll(AbsListView view, int firstVisibleItem,int visibleItemCount, int totalItemCount) {// 发送到用户的监听器mTotalItemCount = totalItemCount;if (mScrollListener != null) {mScrollListener.onScroll(view, firstVisibleItem, visibleItemCount,totalItemCount);}}public void setXListViewListener(IXListViewListener l) {mListViewListener = l;}/** * 你可以监听到列表视图,OnScrollListener 或者这个. 他将会被调用 , 当头部或底部触发的时候 */public interface OnXScrollListener extends OnScrollListener {public void onXScrolling(View view);}/** * 实现这个接口来刷新/负载更多的事件 */public interface IXListViewListener {public void onRefresh();public void onLoadMore();}}

XListViewFooter.xml

package com.example.listviewshangxia;import android.content.Context;import android.util.AttributeSet;import android.view.LayoutInflater;import android.view.View;import android.widget.LinearLayout;import android.widget.TextView;public class XListViewFooter extends LinearLayout {public final static int STATE_NORMAL = 0;public final static int STATE_READY = 1;public final static int STATE_LOADING = 2;private Context mContext;private View mContentView;private View mProgressBar;private TextView mHintView;public XListViewFooter(Context context) {super(context);initView(context);}public XListViewFooter(Context context, AttributeSet attrs) {super(context, attrs);initView(context);}public void setState(int state) {mHintView.setVisibility(View.INVISIBLE);// 开始底部控件都隐藏mProgressBar.setVisibility(View.INVISIBLE);mHintView.setVisibility(View.INVISIBLE);if (state == STATE_READY) {// 如果是第一页状态,那么“查看更多”显示mHintView.setVisibility(View.VISIBLE);mHintView.setText(R.string.xlistview_footer_hint_ready);// 松开显示更多} else if (state == STATE_LOADING) {// 当加载的时候mProgressBar.setVisibility(View.VISIBLE);// 加载进度条显示} else {mHintView.setVisibility(View.VISIBLE);mHintView.setText(R.string.xlistview_footer_hint_normal);// 查看更多}}public void setBottomMargin(int height) {if (height < 0)return;LinearLayout.LayoutParams lp = (LinearLayout.LayoutParams) mContentView.getLayoutParams();lp.bottomMargin = height;mContentView.setLayoutParams(lp);}public int getBottomMargin() {LinearLayout.LayoutParams lp = (LinearLayout.LayoutParams) mContentView.getLayoutParams();return lp.bottomMargin;}/** * normal status */public void normal() {mHintView.setVisibility(View.VISIBLE);mProgressBar.setVisibility(View.GONE);}/** * loading status */public void loading() {mHintView.setVisibility(View.GONE);mProgressBar.setVisibility(View.VISIBLE);}/** * 当禁用拉加载更多隐藏底部视图 */public void hide() {LinearLayout.LayoutParams lp = (LinearLayout.LayoutParams) mContentView.getLayoutParams();lp.height = 0;mContentView.setLayoutParams(lp);}/** * 显示底部视图 */public void show() {LinearLayout.LayoutParams lp = (LinearLayout.LayoutParams) mContentView.getLayoutParams();lp.height = LayoutParams.WRAP_CONTENT;mContentView.setLayoutParams(lp);}private void initView(Context context) {mContext = context;LinearLayout moreView = (LinearLayout) LayoutInflater.from(mContext).inflate(R.layout.xlistview_footer, null);addView(moreView);moreView.setLayoutParams(new LinearLayout.LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT));mContentView = moreView.findViewById(R.id.xlistview_footer_content);mProgressBar = moreView.findViewById(R.id.xlistview_footer_progressbar);mHintView = (TextView) moreView.findViewById(R.id.xlistview_footer_hint_textview);}}

XListViewHeader.Java

package com.example.listviewshangxia;import android.content.Context;import android.util.AttributeSet;import android.view.Gravity;import android.view.LayoutInflater;import android.view.View;import android.view.animation.Animation;import android.view.animation.RotateAnimation;import android.widget.ImageView;import android.widget.LinearLayout;import android.widget.ProgressBar;import android.widget.TextView;public class XListViewHeader extends LinearLayout {private LinearLayout mContainer;private ImageView mArrowImageView;private ProgressBar mProgressBar;private TextView mHintTextView;private int mState = STATE_NORMAL;// 初始状态private Animation mRotateUpAnim;private Animation mRotateDownAnim;private final int ROTATE_ANIM_DURATION = 180;public final static int STATE_NORMAL = 0;public final static int STATE_READY = 1;public final static int STATE_REFRESHING = 2;public XListViewHeader(Context context) {super(context);initView(context);}/** * @param context * @param attrs */public XListViewHeader(Context context, AttributeSet attrs) {super(context, attrs);initView(context);}private void initView(Context context) {// 初始情况,设置下拉刷新view高度为0LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(LayoutParams.FILL_PARENT, 0);// 时间TextViewmContainer = (LinearLayout) LayoutInflater.from(context).inflate(R.layout.xlistview_header, null);addView(mContainer, lp);setGravity(Gravity.BOTTOM);// 找到头部页面里的控件mArrowImageView = (ImageView) findViewById(R.id.xlistview_header_arrow);mHintTextView = (TextView) findViewById(R.id.xlistview_header_hint_textview);mProgressBar = (ProgressBar) findViewById(R.id.xlistview_header_progressbar);mRotateUpAnim = new RotateAnimation(0.0f, -180.0f,Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF,0.5f);mRotateUpAnim.setDuration(ROTATE_ANIM_DURATION);mRotateUpAnim.setFillAfter(true);mRotateDownAnim = new RotateAnimation(-180.0f, 0.0f,Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF,0.5f);mRotateDownAnim.setDuration(ROTATE_ANIM_DURATION);mRotateDownAnim.setFillAfter(true);}// 设置状态public void setState(int state) {if (state == mState)return;if (state == STATE_REFRESHING) { // 显示进度mArrowImageView.clearAnimation();mArrowImageView.setVisibility(View.INVISIBLE);// 不显示图片mProgressBar.setVisibility(View.VISIBLE);// 显示进度条} else { // 显示箭头图片mArrowImageView.setVisibility(View.VISIBLE);mProgressBar.setVisibility(View.INVISIBLE);}switch (state) {case STATE_NORMAL:if (mState == STATE_READY) {// 当状态时准备的时候,显示动画mArrowImageView.startAnimation(mRotateDownAnim);}if (mState == STATE_REFRESHING) {// 当状态显示进度条的时候,清除动画mArrowImageView.clearAnimation();}mHintTextView.setText(R.string.xlistview_header_hint_normal);// 文字提示:下拉刷新break;case STATE_READY:if (mState != STATE_READY) {mArrowImageView.clearAnimation();mArrowImageView.startAnimation(mRotateUpAnim);mHintTextView.setText(R.string.xlistview_header_hint_ready);// 松开刷新数据}break;case STATE_REFRESHING:mHintTextView.setText(R.string.xlistview_header_hint_loading);break;default:}mState = state;}public void setVisiableHeight(int height) {if (height < 0)height = 0;LinearLayout.LayoutParams lp = (LinearLayout.LayoutParams) mContainer.getLayoutParams();lp.height = height;mContainer.setLayoutParams(lp);}public int getVisiableHeight() {return mContainer.getHeight();}}














原创粉丝点击