码迷,mamicode.com
首页 > 移动开发 > 详细

Android——Xlistview上拉刷新下拉加载

时间:2016-03-26 12:35:11      阅读:526      评论:0      收藏:0      [点我收藏+]

标签:

配置网络权限+xutils包+gson包

代码如下:

技术分享

values下修改strings添加 直接粘

<?xml version="1.0" encoding="utf-8"?>
<resources>

    <string name="app_name">XListView刷新</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>

layout下代码

activity_main.xml  直接粘

<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" >

       <com.example.xlistviews.XListView
        android:id="@+id/my_xlist"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        ></com.example.xlistviews.XListView>

</RelativeLayout>

xlist_item.xml     xlistview——item布局

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >

    <ImageView
        android:id="@+id/image_src"
        android:layout_width="100dp"
        android:layout_height="100dp"
        android:layout_alignParentLeft="true"
        android:layout_alignParentTop="true"
        android:src="@drawable/ic_launcher" />

    <TextView
        android:id="@+id/text_title"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignBottom="@id/image_src"
        android:layout_marginBottom="40dp"
        android:layout_toRightOf="@id/image_src"
        android:text="TextView" />

</RelativeLayout>

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:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_centerInParent="true"
            android:gravity="center"
            android:orientation="vertical" android:id="@+id/xlistview_header_text">

            <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>
xlistview_arrow图片

技术分享

src下面

com.example.xlistviews.XListView     创个包xlistviews+类直接粘(包括后面两个 ) 看上面图

/**
 * @file XListView.java
 * @package me.maxwin.view
 * @create Mar 18, 2012 6:28:41 PM
 * @author Maxwin
 * @description An ListView support (a) Pull down to refresh, (b) Pull up to load more.
 *         Implement IXListViewListener, and see stopRefresh() / stopLoadMore().
 */
package com.example.xlistviews;



import com.example.xlistview.R;

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 y
    private Scroller mScroller; // used for scroll back
    private OnScrollListener mScrollListener; // user‘s scroll listener

    // the interface to trigger refresh and load more.
    private IXListViewListener mListViewListener;

    // -- header view
    private XListViewHeader mHeaderView;
    // header view content, use it to calculate the Header‘s height. And hide it
    // when disable pull refresh.
    private RelativeLayout mHeaderViewContent;
    private TextView mHeaderTimeView;
    private int mHeaderViewHeight; // header view‘s height
    private boolean mEnablePullRefresh = true;
    private boolean mPullRefreshing = false; // is refreashing.

    // -- footer view
    private XListViewFooter mFooterView;
    private boolean mEnablePullLoad;
    private boolean mPullLoading;
    private boolean mIsFooterReady = false;
    
    // total list items, used to detect is at the bottom of listview.
    private int mTotalItemCount;

    // for mScroller, scroll back from header or footer.
    private int mScrollBack;
    private final static int SCROLLBACK_HEADER = 0;
    private final static int SCROLLBACK_FOOTER = 1;

    private final static int SCROLL_DURATION = 400; // scroll back duration
    private final static int PULL_LOAD_MORE_DELTA = 50; // when pull up >= 50px
                                                        // at bottom, trigger
                                                        // load more.
    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);

        // init header view
        mHeaderView = new XListViewHeader(context);
        mHeaderViewContent = (RelativeLayout) mHeaderView
                .findViewById(R.id.xlistview_header_content);
        mHeaderTimeView = (TextView) mHeaderView
                .findViewById(R.id.xlistview_header_time);
        addHeaderView(mHeaderView);

        // init footer view
        mFooterView = new XListViewFooter(context);

        // init header height
        mHeaderView.getViewTreeObserver().addOnGlobalLayoutListener(
                new OnGlobalLayoutListener() {
                    @SuppressWarnings("deprecation")
                    @Override
                    public void onGlobalLayout() {
                        mHeaderViewHeight = mHeaderViewContent.getHeight();
                        getViewTreeObserver()
                                .removeGlobalOnLayoutListener(this);
                    }
                });
    }

    @Override
    public void setAdapter(ListAdapter adapter) {
        // make sure XListViewFooter is the last footer view, and only add once.
        if (mIsFooterReady == false) {
            mIsFooterReady = true;
            addFooterView(mFooterView);
        }
        super.setAdapter(adapter);
    }

    /**
     * enable or disable pull down refresh feature.
     * 
     * @param enable
     */
    public void setPullRefreshEnable(boolean enable) {
        mEnablePullRefresh = enable;
        if (!mEnablePullRefresh) { // disable, hide the content
            mHeaderViewContent.setVisibility(View.INVISIBLE);
        } else {
            mHeaderViewContent.setVisibility(View.VISIBLE);
        }
    }

    /**
     * enable or disable pull up load more feature.
     * 
     * @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 "pull up" and "click" will invoke load more.
            mFooterView.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View v) {
                    startLoadMore();
                }
            });
        }
    }

    /**
     * stop refresh, reset header view.
     */
    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);
        }
    }

    /**
     * set last refresh time
     * 
     * @param time
     */
    public void setRefreshTime(String time) {
        mHeaderTimeView.setText(time);
    }

    /**
     * 璋冪敤婊氬姩
     */
    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
    }

    /**
     * 閲嶇疆锟??view 鐨勯珮锟??     */
    private void resetHeaderHeight() {
        int height = mHeaderView.getVisiableHeight();
        if (height == 0) // not visible.
            return;
        // refreshing and header isn‘t shown fully. do nothing.
        if (mPullRefreshing && height <= mHeaderViewHeight) {
            return;
        }
        int finalHeight = 0; // default: scroll back to dismiss header.
        // is refreshing, just scroll back to show all the header.
        if (mPullRefreshing && height > mHeaderViewHeight) {
            finalHeight = mHeaderViewHeight;
        }
        mScrollBack = SCROLLBACK_HEADER;
        mScroller.startScroll(0, height, 0, finalHeight - height,
                SCROLL_DURATION);
        // trigger computeScroll
        invalidate();
    }

    /**
     * 鏇存柊搴曢儴 view 鐨勯珮锟??     */
    private void updateFooterHeight(float delta) {
        int height = mFooterView.getBottomMargin() + (int) delta;
        if (mEnablePullLoad && !mPullLoading) {
            if (height > PULL_LOAD_MORE_DELTA) { // height enough to invoke load
                                                    // more.
                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();
        }
    }

    @SuppressLint("ClickableViewAccessibility")
    private void startLoadMore() {
        mPullLoading = true;
        mFooterView.setState(XListViewFooter.STATE_LOADING);
        if (mListViewListener != null) {
            mListViewListener.onLoadMore();
        }
    }

    @SuppressLint("ClickableViewAccessibility")
    @Override
    public 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();
            //getFirstVisiblePosition() 杩欎釜鏂规硶鏄繑鍥炲綋鍓峫istview鐨勭鍑犱釜鏉$洰涓暟
            if (getFirstVisiblePosition() == 0
                    && (mHeaderView.getVisiableHeight() > 0 || deltaY > 0)) {
                // the first item is showing, header has shown or pull down.
                updateHeaderHeight(deltaY / OFFSET_RADIO);
                invokeOnScrolling();
            } else if (getLastVisiblePosition() == mTotalItemCount - 1
                    && (mFooterView.getBottomMargin() > 0 || deltaY < 0)) {
                // last item, already pulled up or want to pull up.
                updateFooterHeight(-deltaY / OFFSET_RADIO);
            }
            break;
        default:
            mLastY = -1; // reset
            if (getFirstVisiblePosition() == 0) {
                // invoke refresh
                if (mEnablePullRefresh
                        && mHeaderView.getVisiableHeight() > mHeaderViewHeight) {
                    mPullRefreshing = true;
                    mHeaderView.setState(XListViewHeader.STATE_REFRESHING);
                    if (mListViewListener != null) {
                        mListViewListener.onRefresh();
                    }
                }
                resetHeaderHeight();
            } else if (getLastVisiblePosition() == mTotalItemCount - 1) {
                // invoke load more.
                if (mEnablePullLoad
                        && mFooterView.getBottomMargin() > PULL_LOAD_MORE_DELTA) {
                    startLoadMore();
                }
                resetFooterHeight();
            }
            break;
        }
        return super.onTouchEvent(ev);
    }

    @Override
    public void computeScroll() {
        if (mScroller.computeScrollOffset()) {
            if (mScrollBack == SCROLLBACK_HEADER) {
                mHeaderView.setVisiableHeight(mScroller.getCurrY());
            } else {
                mFooterView.setBottomMargin(mScroller.getCurrY());
            }
            postInvalidate();
            invokeOnScrolling();
        }
        super.computeScroll();
    }

    @Override
    public void setOnScrollListener(OnScrollListener l) {
        mScrollListener = l;
    }

    @Override
    public void onScrollStateChanged(AbsListView view, int scrollState) {
        if (mScrollListener != null) {
            mScrollListener.onScrollStateChanged(view, scrollState);
        }
    }

    @Override
    public void onScroll(AbsListView view, int firstVisibleItem,
            int visibleItemCount, int totalItemCount) {
        // send to user‘s listener
        mTotalItemCount = totalItemCount;
        if (mScrollListener != null) {
            mScrollListener.onScroll(view, firstVisibleItem, visibleItemCount,
                    totalItemCount);
        }
    }

    public void setXListViewListener(IXListViewListener l) {
        mListViewListener = l;
    }

    /**
     * you can listen ListView.OnScrollListener or this one. it will invoke
     * onXScrolling when header/footer scroll back.
     */
    public interface OnXScrollListener extends OnScrollListener {
        public void onXScrolling(View view);
    }

    /**
     * implements this interface to get refresh/load more event.
     */
    public interface IXListViewListener {
        public void onRefresh();

        public void onLoadMore();
    }
}

com.example.xlistviews.XListViewFooter    直接粘 上面那个包xlistviews

/**
 * @file XFooterView.java
 * @create Mar 31, 2012 9:33:43 PM
 * @author Maxwin
 * @description XListView‘s footer
 */
package com.example.xlistviews;


import com.example.xlistview.R;

import android.annotation.SuppressLint;
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);
    }
    
    /**
     * hide footer when disable pull load more
     */
    public void hide() {
        LinearLayout.LayoutParams lp = (LinearLayout.LayoutParams)mContentView.getLayoutParams();
        lp.height = 0;
        mContentView.setLayoutParams(lp);
    }
    
    /**
     * show footer
     */
    public void show() {
        LinearLayout.LayoutParams lp = (LinearLayout.LayoutParams)mContentView.getLayoutParams();
        lp.height = LayoutParams.WRAP_CONTENT;
        mContentView.setLayoutParams(lp);
    }
    
    @SuppressWarnings("deprecation")
    @SuppressLint("InflateParams")
    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);
    }
    
    
}

com.example.xlistviews.XListViewHeader    直接粘 上面那个包xlistviews

/**
 * @file XListViewHeader.java
 * @create Apr 18, 2012 5:22:27 PM
 * @author Maxwin
 * @description XListView‘s header
 */
package com.example.xlistviews;


import com.example.xlistview.R;

import android.annotation.SuppressLint;
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);
    }

    @SuppressLint("InflateParams")
    private void initView(Context context) {
        // 鍒濆鎯呭喌锛岃缃笅鎷夊埛鏂皏iew楂樺害涓?
        LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(
                LayoutParams.MATCH_PARENT, 0);
        mContainer = (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();
    }

}

com.example.xlistview.MainActivity       重要看注释

package com.example.xlistview;


import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;

import com.example.adapter.MyBaseAdapter;
import com.example.utils.HttpUtil;
import com.example.vo.Bean;
import com.example.vo.Bean.DataEntity;
import com.example.xlistviews.XListView;
import com.example.xlistviews.XListView.IXListViewListener;
import com.google.gson.Gson;

public class MainActivity extends Activity implements IXListViewListener{
    private XListView my_xlist;
    private int pageIndex = 10;
    private MyBaseAdapter adapter;
    private List<DataEntity> datas;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
//找控件 findViewById();
//直接粘 my_xlist.setPullLoadEnable(
true); my_xlist.setPullRefreshEnable(true); my_xlist.setXListViewListener(this);



//刚进入加载页面
new Thread() { public void run() { try { getdata(); } catch (Exception e) { e.printStackTrace(); } }; }.start(); }
//找控件
private void findViewById() { // TODO Auto-generated method stub my_xlist = (XListView)findViewById(R.id.my_xlist); my_xlist.setOnItemClickListener(new OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { // TODO Auto-generated method stub //此处跳转传值 } }); }
//下拉刷新上拉加载那个方法 @Override
public void onRefresh() { // TODO Auto-generated method stub
//如果想添加上拉刷新时间再在这handler new Thread(){ @Override public void run() { try {
//刷新加载 getdata(); }
catch (Exception e) { e.printStackTrace(); } } }.start();
//当前时间 onLoad(); }
//查看更多那个 @Override
public void onLoadMore() { // TODO Auto-generated method stub new Thread(){ @Override public void run() { super.run(); try {
//加载更多 getdataflush(); runOnUiThread(
new Runnable() { @Override public void run() {
//刷新 adapter.notifyDataSetChanged(); } }); }
catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } }.start();
//当前时间 onLoad(); }
/* * * 设置时间 */ @SuppressLint("SimpleDateFormat") private void onLoad() { my_xlist.stopRefresh(); my_xlist.stopLoadMore(); // 设置日期格式 SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); // 获取当前系统时间 String nowTime = df.format(new Date(System.currentTimeMillis())); // 释放时提示正在刷新时的当前时间 my_xlist.setRefreshTime(nowTime); } /* * * 获得数据; */ private void getdata() throws Exception { String URL = "http://api.expoon.com/AppNews/getNewsList/type/1/p/"+pageIndex; HttpUtil util=new HttpUtil(URL); String newsData = util.getNewsData(); Gson gson=new Gson(); Bean bean = gson.fromJson(newsData, Bean.class); List<DataEntity> data = bean.getData(); datas=data; runOnUiThread(new Runnable() { @Override public void run() { // TODO Auto-generated method stub
//Xlistview 适配
adapter=new MyBaseAdapter(MainActivity.this,datas); my_xlist.setAdapter(adapter); } }); } /** * * 加载数据 * @throws Exception * */ private void getdataflush() throws Exception { pageIndex = pageIndex+1; String URL = "http://api.expoon.com/AppNews/getNewsList/type/1/p/"+pageIndex; HttpUtil util=new HttpUtil(URL); String newsData = util.getNewsData(); Gson gson=new Gson(); Bean bean = gson.fromJson(newsData, Bean.class); List<DataEntity> dataload = bean.getData(); datas.addAll(dataload); } }

com.example.utils.HttpUtil   网上获取数据

package com.example.utils;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
//加载网上数据
public class HttpUtil {
    private String url;
    private String string;

    public HttpUtil(String url) {
        super();
        this.url = url;
    }
    public String getNewsData() throws Exception{
        HttpClient client=new DefaultHttpClient();
        HttpGet get=new HttpGet(url);
        HttpResponse execute = client.execute(get);
        if(execute.getStatusLine().getStatusCode()==200){
            HttpEntity entity = execute.getEntity();
            string = EntityUtils.toString(entity, "utf-8");
        }
        return string;
    }
}

com.example.vo.Bean   VO类

package com.example.vo;

import java.util.List;

/**
 * Created by lenovo on 2016/3/19.
 */
public class Bean {

    /**
     * status : 1 info : 获取内容成功 data :
     * [{"news_id":"13758","news_title":"2016中国年装修综合博览会 2月正式开展","news_summary":"
     * 由上海家装标杆企业联盟、上海十大家装领军企业主办,上海装饰装修行业协会支持协办的将于2016年2月11日\u201413日
     * (大年初","pic_url
     * ":"http://f.expoon.com/sub/news/2016/01/13/765424_230x162_0.jpg"},
     * {"news_id":"13757","news_title":"第79届全国汽车配件交易会","news_summary":
     * "由中国机械工业联合会、中国汽车工业配件销售有限公司共同主办的商务部重点支
     * 持引导展会第79届全国汽车配件交易会将于5月13","pic_url":"
     * http://f.expoon.com/sub/news/2016/01/12/827065_230x162_0.jpg"}
     * ,{"news_id":"13756","news_title":"2016年河北各地商品年货展火热来袭","news_summary":"
     * 虽说距离阴历新年还有一个月的时间,河北各地的商品年货展已经迫不及待的开始举办了!各地的朋友们不如带着一家老小,准备扫荡年","
     * pic_url":"
     * http://f.expoon.com/sub/news/2016/01/12/730350_230x162_0.jpg"},{"
     * news_id":"13754","news_title":
     * "青岛首届童博会15日登场 三天预计吸引观众10万","news_summary":"宝贝嘉年华\u2014\u2014萌宠闹新春!
     * 由青岛大众网主办的青岛市首届儿童产业博览会将于1月15日在青岛银海国际会展中心闪亮登场
     * ,在为期","pic_url":"http://f.expoon
     * .com/sub/news/2016/01/12/527415_230x162_0.jpg"},
     * {"news_id":"13753","news_title"
     * :"第十三届中国(寿光)国际蔬菜科技博览会召开新闻发布会","news_summary":"据编者在第十三届中国
     * (寿光)国际蔬菜科技博览会新闻发布会上了解到,以\u201c绿色、科技、未来\u201d为主题的第十三届中国(寿光)国际","pic_url":
     * "http://f.expoon.com/sub/news/2016/01/12/993785_230x162_0.jpg"
     * },{"news_id":"13752","news_title":"第四届武汉放心酒展览交易会本周开幕","news_summary":
     * "春节将近,市民打年货又多了一个好去处。1月15日至1月18日,2016第四届湖北(武汉)放心酒展览交易会将在武汉国际会展","pic_url":
     * "http://f.expoon.com/sub/news/2016/01/12/932804_230x162_0.jpg"
     * },{"news_id"
     * :"13751","news_title":"2016中国(菏泽)农资交易会 4月盛大举办","news_summary":
     * "近日,第十一届中国(菏泽)农资交易会组委会,在菏泽市举行了新闻发布会,宣布2016中国(菏泽)农资交易会将于4月8日--","pic_url":
     * "http://f.expoon.com/sub/news/2016/01/12/817108_230x162_0.jpg"
     * },{"news_id":"13749","news_title":"2016中国电子信息博览会在美举办推介会","news_summary":
     * "由工业和信息化部和深圳市人民政府共同主办的中国电子信息博览会(英文全称:China Information Techno","pic_url":
     * "http://f.expoon.com/sub/news/2016/01/11/321735_230x162_0.jpg"
     * },{"news_id"
     * :"13748","news_title":"第五届哈尔滨新能源电动车及零配件展1月17日举行","news_summary"
     * :"由哈尔滨市贸促会主办,黑龙江省轻工业援外处、黑龙江省电动车流通商会协办、哈尔滨太平洋展览公司承办的第五届哈尔滨新能源电动"
     * ,"pic_url":
     * "http://f.expoon.com/sub/news/2016/01/11/829038_230x162_0.jpg"}
     * ,{"news_id":"13747","news_title":"2016中国·聊城首届微商博览会","news_summary":
     * "近日,中国·聊城首届微商博览会新闻发布会在经济技术开发区管理委员会举办。为了展现经济技术开发区微商产业过去一年中在社会各","pic_url":
     * "http://f.expoon.com/sub/news/2016/01/11/165821_230x162_0.jpg"
     * },{"news_id"
     * :"13746","news_title":"2016年全球机器人博览会 你与机器人有个约会!","news_summary":
     * "1月7日,\u201c2016年全球机器人博览会郑州站\u201d新闻发布会在建业五栋大楼5D生活馆举行。据悉,由河南省经济技术协作企业联合"
     * ,"pic_url"
     * :"http://f.expoon.com/sub/news/2016/01/11/359757_230x162_0.jpg"}
     * ,{"news_id"
     * :"13745","news_title":"第八届合肥年货展16日开幕 热带水果航空直运年货展","news_summary"
     * :"一年一度的年货盛会,将于1月16-1月31日在安徽国际会展中心与广大市民相约。16天的狂欢,给城市里的年味添了一道浓浓的"
     * ,"pic_url":
     * "http://f.expoon.com/sub/news/2016/01/11/312514_230x162_0.jpg"}
     * ,{"news_id":"13743","news_title":"第十八届中原电动车博览会\u201c观众邀请万里行\u201d正在进行",
     * "news_summary":
     * "\u201c第十八届中原电动车·三轮车·电动汽车博览会\u201d,将于2016年4月16日至18日在郑州市郑汴路中原国际博览中心闪亮登场。"
     * ,"pic_url"
     * :"http://f.expoon.com/sub/news/2016/01/08/353701_230x162_0.jpg"}
     * ,{"news_id":"13741","news_title":"第三届兰州年货会 即将开幕","news_summary":
     * "距离第三届兰州年货会开幕的日子仅有不到两周的时间,昨天,记者从年货会组委会获悉,为将年货会打造成安全、优质、高效的年货购","pic_url":
     * "http://f.expoon.com/sub/news/2016/01/08/242001_230x162_0.jpg"
     * },{"news_id"
     * :"13740","news_title":"昆明金殿第28届山茶花展16日开幕 金殿赏花正当时","news_summary"
     * :"昨日,昆明金殿名胜区传来好消息:16日起,至美春城赋·金殿茶花秀暨金殿第28届山茶花展将正式开展,并持续至3月20日。花"
     * ,"pic_url":
     * "http://f.expoon.com/sub/news/2016/01/08/757474_230x162_0.jpg"}
     * ,{"news_id":"13739","news_title":"第五届房地产博览会将于本月15日举办","news_summary":
     * "据悉,以\u201c科技提升品质·创新成就未来\u201d为主题,2016重庆第五届房地产博览会将于1月15日-17日在南坪国际会议展览中心"
     * ,"pic_url"
     * :"http://f.expoon.com/sub/news/2016/01/08/826426_230x162_0.jpg"}
     * ,{"news_id":"13738","news_title":"消费升级 上海尚品家居展呈现国货精品","news_summary":
     * "在即将于2016年8月6\u20148日于上海新国际展馆举行的上海尚品家居装饰展上,将有一批中国制造的家居消费品,以不逊于国际水准"
     * ,"pic_url"
     * :"http://f.expoon.com/sub/news/2016/01/08/296295_230x162_0.jpg"}
     * ,{"news_id":"13737","news_title":"迎春盛典 深圳礼品展节庆用礼暖洋洋","news_summary":
     * "新春佳节到,礼尚往来,互相祝福是中华民族的优良传统。不论是商务馈赠,员工福利还是企业团购,深圳礼品家居展都集中了优秀的供","pic_url":
     * "http://f.expoon.com/sub/news/2016/01/08/989604_230x162_0.jpg"
     * },{"news_id"
     * :"13736","news_title":"2016第7届中国 (郑州)国际消防展组委会新春贺词","news_summary":
     * "\u201c金猴迎春来、新年展宏图\u201d,值此新春佳节来临之际,CZFE郑州国际消防展组委会向长期以来关注郑州消防展的各级领导、媒体朋"
     * ,"pic_url"
     * :"http://f.expoon.com/sub/news/2016/01/07/832584_230x162_0.jpg"}
     * ,{"news_id":"13733","news_title":"78年历史的香港工展会8月亮相大连","news_summary":
     * "2016香港时尚产品博览·大连工展会将于8月底在大连世界博览广场上演,预计将有200家香港企业来连参展,让大连市民体验正","pic_url":
     * "http://f.expoon.com/sub/news/2016/01/07/270195_230x162_0.jpg"}]
     */

    private int status;
    private String info;
    /**
     * news_id : 13758 news_title : 2016中国年装修综合博览会 2月正式开展 news_summary :
     * 由上海家装标杆企业联盟、上海十大家装领军企业主办,上海装饰装修行业协会支持协办的将于2016年2月11日—13日(大年初 pic_url :
     * http://f.expoon.com/sub/news/2016/01/13/765424_230x162_0.jpg
     */

    private List<DataEntity> data;

    public void setStatus(int status) {
        this.status = status;
    }

    public void setInfo(String info) {
        this.info = info;
    }

    public void setData(List<DataEntity> data) {
        this.data = data;
    }

    public int getStatus() {
        return status;
    }

    public String getInfo() {
        return info;
    }

    public List<DataEntity> getData() {
        return data;
    }

    public static class DataEntity {
        private String news_id;
        private String news_title;
        private String news_summary;
        private String pic_url;

        public void setNews_id(String news_id) {
            this.news_id = news_id;
        }

        public void setNews_title(String news_title) {
            this.news_title = news_title;
        }

        public void setNews_summary(String news_summary) {
            this.news_summary = news_summary;
        }

        public void setPic_url(String pic_url) {
            this.pic_url = pic_url;
        }

        public String getNews_id() {
            return news_id;
        }

        public String getNews_title() {
            return news_title;
        }

        public String getNews_summary() {
            return news_summary;
        }

        public String getPic_url() {
            return pic_url;
        }
    }
}

com.example.adapter.MyBaseAdapter   Xlistview适配

package com.example.adapter;

import java.util.List;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;

import com.example.vo.Bean.DataEntity;
import com.example.xlistview.R;
import com.lidroid.xutils.BitmapUtils;

public class MyBaseAdapter extends BaseAdapter {
    Context context;
    List<DataEntity> data;
    public MyBaseAdapter(Context context, List<DataEntity> data) {
        // TODO Auto-generated constructor stub
        this.context=context;
        this.data=data;
    }

    @Override
    public int getCount() {
        // TODO Auto-generated method stub
        return data.size();
    }

    @Override
    public Object getItem(int arg0) {
        // TODO Auto-generated method stub
        return data.get(arg0);
    }

    @Override
    public long getItemId(int arg0) {
        // TODO Auto-generated method stub
        return arg0;
    }

    @Override
    public View getView(int arg0, View convertView, ViewGroup arg2) {
        // TODO Auto-generated method stub
        viewholder vh;
        if(convertView==null){
            convertView=LayoutInflater.from(context).inflate(R.layout.xlist_item, null);
            vh=new viewholder();
            vh.image=(ImageView) convertView.findViewById(R.id.image_src);
            vh.title=(TextView) convertView.findViewById(R.id.text_title);
            convertView.setTag(vh);
        }else{
            vh=(viewholder) convertView.getTag();
        }
        BitmapUtils bitmapUtils=new BitmapUtils(context);
        bitmapUtils.display(vh.image, data.get(arg0).getPic_url());
        vh.title.setText(data.get(arg0).getNews_title());
        return convertView;
    }
    class viewholder{
        ImageView image;
        TextView title;
    }
}

 

Android——Xlistview上拉刷新下拉加载

标签:

原文地址:http://www.cnblogs.com/1426837364qqcom/p/5299637.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!