使用第三方类XListView,实现ListView的加载刷新,提示

    使用第三方类XListView,实现ListView的加载刷新,提示
    首先 ,file - new - new Module 新建一个Module,名字自定义
    java         workSpace -- project
    android      project -- Module
    在 Module 的 src 目录下有
    1. androidTest
    2. main
    3. test
    在mian 目录下面java 目录下有,新建一个包名,最好是按照路径来命名
    在此目录下引三个类
    XListView
    XListViewFooter
    XListViewHeader
    最后选择file--Progect Structure -- app---dependencies-- "+"
    这里有三个选项
    library dependencies--在线加载,输入加载的网站即可在线加载
    File dependency -- 引进lib 目录下的第三方包
    Module dependency -- 引进Module ,选他,弹出的对话框里有刚刚新建的Module,确认就行了
    
    
    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() {
                    @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
    }

    /**
     * reset header view's height.
     */
    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();
    }

    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();
        }
    }

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

    @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();
            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();
    }
}
==================================
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 ;
        LayoutParams lp = (LayoutParams)mContentView.getLayoutParams();
        lp.bottomMargin = height;
        mContentView.setLayoutParams(lp);
    }

    public int getBottomMargin() {
        LayoutParams lp = (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() {
        LayoutParams lp = (LayoutParams)mContentView.getLayoutParams();
        lp.height = 0;
        mContentView.setLayoutParams(lp);
    }

    /**
     * show footer
     */
    public void show() {
        LayoutParams lp = (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 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);
    }
    
    
}
===========================================
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高度为0
        LayoutParams lp = new LayoutParams(LayoutParams.FILL_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;
        LayoutParams lp = (LayoutParams) mContainer
                .getLayoutParams();
        lp.height = height;
        mContainer.setLayoutParams(lp);
    }

    public int getVisiableHeight() {
        return mContainer.getHeight();
    }

}
==============================================
public class MainActivity extends AppCompatActivity implements XListView.IXListViewListener{
    /**
     *   1.头条新闻列表接口
     参数定义:
     int pageNo = 0; //页号 ,表示第几页,第一页从0开始
     int pageSize = 20; //页大小,显示每页多少条数据
     String news_type_id = "T1348647909107";  //新闻类型标识, 此处表示头条新闻

     Url请求地址: "http://c.m.163.com/nc/article/headline/"+ news_type_id +pageNo*pageSize+ "-"  +pageSize+ ".html"

     请求方式:Get

     例如: http://c.m.163.com/nc/article/headline/T1348647909107/0-20.html        //表示请求头条新闻第一页20条数据
     http://c.m.163.com/nc/article/headline/T1348647909107/20-20.html    //表示请求头条新闻第二页20条数据
     http://c.m.163.com/nc/article/headline/T1348647909107/40-20.html    //表示请求头条新闻第三页20条数据
     */
    private static final int PAGE_SIZE = 20; //每页数据个数
    int pageNo = 0; //页号 ,表示第几页,第一页从0开始
    int pageSize = 20; //页大小,显示每页多少条数据
    String news_type_id = "T1348647909107";  //新闻类型标识, 此处表示头条新闻
    private int mCurrentPageNo = 0; //当前页号
    private int mTotalPageCount = 5; //总页数
    private XListView mListView;
    private MyPagerAdapter mPagerAdapter;
    public SimpleDateFormat simpleDateFormat = new SimpleDateFormat("HH:mm:ss");//hh 小写是十二进制,HH 大写是24进制
    private  String baseUrl = "http://c.m.163.com/nc/article/headline/"+ news_type_id +"/"+pageNo*pageSize+ "-"  +pageSize+ ".html";
    private ConnectionUtil connectionUtil;
    ArrayList<news> list = new ArrayList<>();
    ArrayList<Ads> listAds = new ArrayList<>();
    JSONArray ads;

    TextView mTextView;
    int length;
    Ads a ;
    View view1 = null;
    View view2;
    View view3;
    ViewPager mviewpager;
    ImageView imageViewone,imageViewtwo,imageViewthree;
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mListView = (XListView) findViewById(R.id.myXlistview);
        mviewpager = (ViewPager) findViewById(R.id.myXlistview_viewpager);
        mTextView = (TextView) findViewById(R.id.myXlistview_txt);



        connectionUtil = new ConnectionUtil(this);
        mPagerAdapter = new MyPagerAdapter(this);
        mListView.setAdapter(mPagerAdapter);

        mListView.setXListViewListener(this);
        mListView.setPullLoadEnable(true); //上拉加载更多开关
        mListView.setPullRefreshEnable(true);   //下拉刷新开关

        getDataLists(mCurrentPageNo);


        LayoutInflater layoutInflater = LayoutInflater.from(this);
        view1 = layoutInflater.inflate(R.layout.activity_xlistview_viewone_layout, null);
        view2 = layoutInflater.inflate(R.layout.activity_xlistview_viewtwo_layout, null);
        view3 = layoutInflater.inflate(R.layout.activity_xlistview_viewthree_layout, null);
        List<View> list = new ArrayList<>();
        // TODO: 2016/6/14  加view1是因为(R.layout.activity_demo_meituan_layout)已经解析了
        // todo 直接findViewById(R.id.gridview1)会在里面寻找,就会报空指针错
        list.add(view1);
        list.add(view2);
        list.add(view3);

        ViewAdapter adapter = new ViewAdapter(list);
        Logs.e("adapter>>>>>>>"+adapter);
        Logs.e("mviewpager>>>>"+mviewpager);
        Logs.e("list>>>>"+list);
        mviewpager.setAdapter(adapter);



        mviewpager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }


            public void onPageSelected(int position) {

                switch (position) {
                    case 0:
                        imageViewone = (ImageView) view1.findViewById(R.id.xlistview_imgone);
                        a = listAds.get(0);

                        String texone = a.getTitle();
                        mTextView.setText(texone);

                        break;
                    case 1:
                        imageViewtwo = (ImageView)view2.findViewById(R.id.xlistview_imgtwo);
                        a = listAds.get(1);
                        String imgtwo = a.getImgsrc();
                        String tex = a.getTitle();
                        Logs.e("tex>>>>"+tex);
                        mTextView.setText(tex);
                        Logs.e("imgtwo>>>>"+imgtwo);
                        Glide.with(MainActivity.this).load(imgtwo).into(imageViewtwo);//对于直接从网络取数
                        break;
                    case 2:
                        imageViewthree = (ImageView)view3.findViewById(R.id.xlistview_imgthree);
                        a = listAds.get(2);
                        String imgthree = a.getImgsrc();
                        String texThree = a.getTitle();
                        mTextView.setText(texThree);
                        Logs.e("texThree>>>>"+texThree);
                        Logs.e("imgthree>>>>"+imgthree);
                        Glide.with(MainActivity.this).load(imgthree).into(imageViewthree);//对于直接从网络取数据的图片使用第三方包,
                        break;
                }
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });



    }

    public void onRefresh() {
        Logs.e("onRefresh");
        pageNo = 0;
        getDataLists(pageNo);
        mListView.stopRefresh();
    }

    @Override
    public void onLoadMore() {
        ++pageNo;
        if (pageNo > mTotalPageCount) {
            pageNo = mTotalPageCount;
            mListView.stopLoadMore();
            Toast.makeText(this, "已加载到最后一页", Toast.LENGTH_SHORT).show();
            return;
        }
        Logs.e("pageNo>>>"+pageNo);
        getDataLists(pageNo);

    }
    public void getDataLists(int pageNo) {
        String baseUrl = "http://c.m.163.com/nc/article/headline/"+ news_type_id +"/"+pageNo*pageSize+ "-"  +pageSize+ ".html";
        connectionUtil.asyncConnect(baseUrl, ConnectionUtil.Mothod.GET, new ConnectionUtil.HttpConnectionInterface() {

            public void excute(String cont) {
                if (cont == null) {
                    Toast.makeText(MainActivity.this, "请求出错!", Toast.LENGTH_SHORT).show();
                    return;
                }
                setViewpage(cont);

                Logs.e("content :" + cont);
                mListView.stopLoadMore();
                mListView.stopRefresh();
                mListView.setRefreshTime(simpleDateFormat.format(new Date(System.currentTimeMillis())));

                Gson gson = new Gson();
                Content conten = gson.fromJson(cont, Content.class);
                mTotalPageCount = 5;
                ArrayList<news> list = conten.getT1348647909107();
                mPagerAdapter.addDataList(list);


            }

        });

    }
    public void setViewpage(String content){
        JSONObject jsonObject = null;
        try {
            jsonObject = new JSONObject(content);
            JSONArray jsonObj = jsonObject.getJSONArray("T1348647909107");
            length = jsonObj.length();
            JSONObject jsonObjItemads = jsonObj.getJSONObject(0);
            ads= jsonObjItemads.getJSONArray("ads");
            int len = ads.length();
            Logs.e("ads>>>>"+ads);
            Logs.e("len>>>>"+len);
            for(int g = 0;g<len;g++) {
                JSONObject jsonObjItem = jsonObj.getJSONObject(g);
                String imgsrc = jsonObjItem.getString("imgsrc");
                String tex = jsonObjItem.getString("title");
                Logs.e("imgsrc>>>>" + imgsrc);
                Ads a = new Ads();
                a.setImgsrc(imgsrc);
                a.setTitle(tex);
                listAds.add(a);


            }

        } catch (JSONException e) {
            e.printStackTrace();
        }
        imageViewone = (ImageView) view1.findViewById(R.id.xlistview_imgone);
        a = listAds.get(0);
        String img = a.getImgsrc();
        String tex = a.getTitle();
        mTextView.setText(tex);
        Logs.e("img>>>>"+img);
        Glide.with(MainActivity.this).load(img).into(imageViewone);//对于从网络取数据的图片使用第三方包,还可以缓存

    }



    class MyPagerAdapter extends BaseAdapter {
        List<news> list = new ArrayList<>();
        LayoutInflater layoutInflater;
        public MyPagerAdapter(Context context){
            this.layoutInflater = LayoutInflater.from(context);
        }
        public void SetDatalist(List<news> list){
            this.list = list;
            notifyDataSetChanged();
        }
        public void addDataList(List<news> list){
            this.list.addAll(list);
            notifyDataSetChanged();
        }
        public int getCount() {
            return list.size();
        }

        @Override
        public Object getItem(int i) {
            return list.get(i);
        }

        @Override
        public long getItemId(int i) {
            return i;
        }

        @Override
        public View getView(int i, View view, ViewGroup viewGroup) {
            HoldView holdView;
            if(view == null){
                view = layoutInflater.inflate(R.layout.activity_item_layout,null);
                ImageView imageView = (ImageView) view.findViewById(R.id.item_img);
                TextView title = (TextView) view.findViewById(R.id.item_title);
                TextView content = (TextView) view.findViewById(R.id.item_content);

                holdView = new HoldView();
                holdView.pic = imageView;
                holdView.title = title;
                holdView.content = content;
                view.setTag(holdView);
            }
            holdView = (HoldView) view.getTag();
            news n = (news) getItem(i);
            String title = n.getTitle();
            String content = n.getDigest();
            String img = n.getImgsrc();

            holdView.title.setText(title);
            holdView.content.setText(content);
            Glide.with(MainActivity.this).load(img).into(holdView.pic);//对于直接从网络取数据的图片使用第三方包,还可以缓存
            return view;
        }
    }
    public class HoldView{
        ImageView pic;
        TextView title;
        TextView content;
    }

    public class ViewAdapter extends PagerAdapter {
        List<View> list = new ArrayList<>();

        public ViewAdapter(List<View> list) {
            this.list = list;
        }

        public int getCount() {
            return list.size();
        }

        @Override
        public boolean isViewFromObject(View view, Object object) {
            return view == object;
        }

        public Object instantiateItem(ViewGroup container, int position) {
            View view = list.get(position);
            container.addView(view);
            return view;
        }

        public void destroyItem(ViewGroup container, int position, Object object) {
            View view = list.get(position);
            container.removeView(view);
        }
    }

}
==============================
对于网络的数据转化成对象的相应类
public class Content {

    public ArrayList<news> T1348647909107;

    public ArrayList<news> getT1348647909107() {
        return T1348647909107;
    }

    public void setT1348647909107(ArrayList<news> t1348647909107) {
        T1348647909107 = t1348647909107;
    }
}
========
public class news {
    String title;
    String imgsrc;
    String digest;
    ArrayList<Ads> ads;

    public ArrayList<Ads> getAds() {
        return ads;
    }

    public void setAds(ArrayList<Ads> ads) {
        this.ads = ads;
    }

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    public String getImgsrc() {
        return imgsrc;
    }

    public void setImgsrc(String imgsrc) {
        this.imgsrc = imgsrc;
    }

    public String getDigest() {
        return digest;
    }

    public void setDigest(String digest) {
        this.digest = digest;
    }
}
=======
public class Ads {
    String title;
    String imgsrc;

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    public String getImgsrc() {
        return imgsrc;
    }

    public void setImgsrc(String imgsrc) {
        this.imgsrc = imgsrc;
    }
}
====================================
自定义封装的工具类,实现异步联网取数据
 Created by scxh on 2016/7/28.
 */
public class ConnectionUtil {
    public static final String STRING_CACHE_NAME = "com.example.scxh.myapp.Utils";
    private Context mContext;
    private static boolean isCache = true;
    public enum Mothod {
        GET,POST
    }
    public enum Cache {
        TRUE,FALSE
    }
    public ConnectionUtil(Context context){
        mContext = context;
    }
    public interface HttpConnectionInterface {
        void excute(String content) throws JSONException;
    }

    /**
     * 无参无缓存请求
     *
     * @param httpUrl
     * @param method
     * @param httpConnectionInterface
     */
    public void asyncConnect(final String httpUrl, final Mothod method, final HttpConnectionInterface httpConnectionInterface) {
        asyncConnect(httpUrl, null, method, Cache.FALSE, httpConnectionInterface);
    }

    /**
     * 无参有缓存
     *
     * @param httpUrl
     * @param method
     * @param httpConnectionInterface
     */
    public void asyncConnect(final String httpUrl, final Mothod method, Cache isCache, final HttpConnectionInterface httpConnectionInterface) {
        asyncConnect(httpUrl, null, method, isCache, httpConnectionInterface);
    }

    /**
     * 有参无缓存
     *
     * @param httpUrl
     * @param paramtMap
     * @param method
     * @param httpConnectionInterface
     */
    public void asyncConnect(final String httpUrl, final HashMap<String, String> paramtMap, final Mothod method, final HttpConnectionInterface httpConnectionInterface) {
        asyncConnect(httpUrl, paramtMap, method, Cache.FALSE, httpConnectionInterface);
    }

    /**
     * 有参有缓存请求
     * 异步联网获取Http响应字符串数据
     *
     * @param httpUrl
     * @param
     * @param method
     * @param httpConnectionInterface
     */
    public void asyncConnect(final String httpUrl, final HashMap<String,String> paramMap, final ConnectionUtil.Mothod method, final Cache isCache,
                             final ConnectionUtil.HttpConnectionInterface httpConnectionInterface){
        new AsyncTask<String,Void,String>(){
            @Override
            protected String doInBackground(String... strings) {
                String Urls = strings[0];
                return doHttpConnection(Urls,paramMap,method,isCache);
            }
            protected void onPostExecute(String content){
                try {
                    httpConnectionInterface.excute(content);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        }.execute(httpUrl);
    }
    public String doHttpConnection(String httpUrl, HashMap<String,String> paramMap, ConnectionUtil.Mothod mothod,Cache isCache){
        if(mothod == Mothod.GET){
            if(paramMap != null){
                String paramUrl = "?";
                paramUrl = doParameterHttp(paramUrl,paramMap);
                httpUrl = httpUrl + paramUrl;
            }
            return doGetPostHttp(httpUrl,paramMap,mothod,isCache);
        }else {
            return doGetPostHttp(httpUrl,paramMap,mothod,isCache);
        }
    }
    public String doParameterHttp(String httpUrl,HashMap<String,String> paramMap){
        for(String key:paramMap.keySet()){
            String value = paramMap.get(key);
            httpUrl = httpUrl + key + "=" + value + "&";
        }
        httpUrl = httpUrl.substring(0,httpUrl.length()-1);
        return httpUrl;
    }
    public String doGetPostHttp(String httpUrl,HashMap<String,String> paramMap,Mothod mothod,Cache isCache){
        String message = "";
        HttpURLConnection httpURLConnection = null;
        try {
            URL url = new URL(httpUrl);
            Logs.e("httpUrl>>>"+httpUrl);
            httpURLConnection = (HttpURLConnection) url.openConnection();
            if(mothod == Mothod.GET){
                httpURLConnection.setRequestMethod("GET");
            }else {
                httpURLConnection.setRequestMethod("POST");
            }
           httpURLConnection.setConnectTimeout(5000);//连接超时时间
            httpURLConnection.setReadTimeout(5000); //读数据超时
            httpURLConnection.connect();

            if(mothod == Mothod.POST){
                // post请求的参数
                if(paramMap != null){
                    String data = doParameterHttp("",paramMap);//userName=admin&passWord=123456
                    // 获得一个输出流,向服务器写数据,默认情况下,系统不允许向服务器输出内容
                    OutputStream outputStream = httpURLConnection.getOutputStream();
                    outputStream.write(data.getBytes());
                    outputStream.flush();
                    outputStream.close();
                }
            }

            int code = httpURLConnection.getResponseCode();
            Logs.e("code>>>>"+code);
            if(code == HttpURLConnection.HTTP_OK){
                InputStream inputStream = httpURLConnection.getInputStream();
                message = readInput(inputStream);
                if(isCache == Cache.TRUE){
                    mContext.getSharedPreferences(STRING_CACHE_NAME,Context.MODE_PRIVATE).edit().putString(httpUrl,message).commit();
                }
            }

        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
            String cacheContent = mContext.getSharedPreferences(STRING_CACHE_NAME,Context.MODE_PRIVATE).getString(httpUrl,null);
            return cacheContent;
        }finally {
            httpURLConnection.disconnect();
        }
        return message;
    }
    /**
     * 输入流转字符串
     *
     * @param is
     * @return
     */
    public String readInput(InputStream is) {
        Reader reader = new InputStreamReader(is);  //字节转字符流
        BufferedReader br = new BufferedReader(reader); //字符缓存流

        StringBuilder sb = new StringBuilder();
        String line = null;
        try {
            while ((line = br.readLine()) != null) {
                sb.append(line);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                br.close();
                reader.close();
                is.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        return sb.toString();
    }

}
    使用第三方类XListView,实现ListView的加载刷新,提示
    首先 ,file - new - new Module 新建一个Module,名字自定义
    java         workSpace -- project
    android      project -- Module
    在 Module 的 src 目录下有
    1. androidTest
    2. main
    3. test
    在mian 目录下面java 目录下有,新建一个包名,最好是按照路径来命名
    在此目录下引三个类
    XListView
    XListViewFooter
    XListViewHeader
    最后选择file--Progect Structure -- app---dependencies-- "+"
    这里有三个选项
    library dependencies--在线加载,输入加载的网站即可在线加载
    File dependency -- 引进lib 目录下的第三方包
    Module dependency -- 引进Module ,选他,弹出的对话框里有刚刚新建的Module,确认就行了
   
   
    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() {
                    @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
    }

    /**
     * reset header view's height.
     */
    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();
    }

    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();
        }
    }

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

    @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();
            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();
    }
}
==================================
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 ;
        LayoutParams lp = (LayoutParams)mContentView.getLayoutParams();
        lp.bottomMargin = height;
        mContentView.setLayoutParams(lp);
    }

    public int getBottomMargin() {
        LayoutParams lp = (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() {
        LayoutParams lp = (LayoutParams)mContentView.getLayoutParams();
        lp.height = 0;
        mContentView.setLayoutParams(lp);
    }

    /**
     * show footer
     */
    public void show() {
        LayoutParams lp = (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 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);
    }
   
   
}
===========================================
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高度为0
        LayoutParams lp = new LayoutParams(LayoutParams.FILL_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;
        LayoutParams lp = (LayoutParams) mContainer
                .getLayoutParams();
        lp.height = height;
        mContainer.setLayoutParams(lp);
    }

    public int getVisiableHeight() {
        return mContainer.getHeight();
    }

}
==============================================
public class MainActivity extends AppCompatActivity implements XListView.IXListViewListener{
    /**
     *   1.头条新闻列表接口
     参数定义:
     int pageNo = 0; //页号 ,表示第几页,第一页从0开始
     int pageSize = 20; //页大小,显示每页多少条数据
     String news_type_id = "T1348647909107";  //新闻类型标识, 此处表示头条新闻

     Url请求地址: "http://c.m.163.com/nc/article/headline/"+ news_type_id +pageNo*pageSize+ "-"  +pageSize+ ".html"

     请求方式:Get

     例如: http://c.m.163.com/nc/article/headline/T1348647909107/0-20.html        //表示请求头条新闻第一页20条数据
     http://c.m.163.com/nc/article/headline/T1348647909107/20-20.html    //表示请求头条新闻第二页20条数据
     http://c.m.163.com/nc/article/headline/T1348647909107/40-20.html    //表示请求头条新闻第三页20条数据
     */
    private static final int PAGE_SIZE = 20; //每页数据个数
    int pageNo = 0; //页号 ,表示第几页,第一页从0开始
    int pageSize = 20; //页大小,显示每页多少条数据
    String news_type_id = "T1348647909107";  //新闻类型标识, 此处表示头条新闻
    private int mCurrentPageNo = 0; //当前页号
    private int mTotalPageCount = 5; //总页数
    private XListView mListView;
    private MyPagerAdapter mPagerAdapter;
    public SimpleDateFormat simpleDateFormat = new SimpleDateFormat("HH:mm:ss");//hh 小写是十二进制,HH 大写是24进制
    private  String baseUrl = "http://c.m.163.com/nc/article/headline/"+ news_type_id +"/"+pageNo*pageSize+ "-"  +pageSize+ ".html";
    private ConnectionUtil connectionUtil;
    ArrayList<news> list = new ArrayList<>();
    ArrayList<Ads> listAds = new ArrayList<>();
    JSONArray ads;

    TextView mTextView;
    int length;
    Ads a ;
    View view1 = null;
    View view2;
    View view3;
    ViewPager mviewpager;
    ImageView imageViewone,imageViewtwo,imageViewthree;
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mListView = (XListView) findViewById(R.id.myXlistview);
        mviewpager = (ViewPager) findViewById(R.id.myXlistview_viewpager);
        mTextView = (TextView) findViewById(R.id.myXlistview_txt);



        connectionUtil = new ConnectionUtil(this);
        mPagerAdapter = new MyPagerAdapter(this);
        mListView.setAdapter(mPagerAdapter);

        mListView.setXListViewListener(this);
        mListView.setPullLoadEnable(true); //上拉加载更多开关
        mListView.setPullRefreshEnable(true);   //下拉刷新开关

        getDataLists(mCurrentPageNo);


        LayoutInflater layoutInflater = LayoutInflater.from(this);
        view1 = layoutInflater.inflate(R.layout.activity_xlistview_viewone_layout, null);
        view2 = layoutInflater.inflate(R.layout.activity_xlistview_viewtwo_layout, null);
        view3 = layoutInflater.inflate(R.layout.activity_xlistview_viewthree_layout, null);
        List<View> list = new ArrayList<>();
        // TODO: 2016/6/14  加view1是因为(R.layout.activity_demo_meituan_layout)已经解析了
        // todo 直接findViewById(R.id.gridview1)会在里面寻找,就会报空指针错
        list.add(view1);
        list.add(view2);
        list.add(view3);

        ViewAdapter adapter = new ViewAdapter(list);
        Logs.e("adapter>>>>>>>"+adapter);
        Logs.e("mviewpager>>>>"+mviewpager);
        Logs.e("list>>>>"+list);
        mviewpager.setAdapter(adapter);



        mviewpager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }


            public void onPageSelected(int position) {

                switch (position) {
                    case 0:
                        imageViewone = (ImageView) view1.findViewById(R.id.xlistview_imgone);
                        a = listAds.get(0);

                        String texone = a.getTitle();
                        mTextView.setText(texone);

                        break;
                    case 1:
                        imageViewtwo = (ImageView)view2.findViewById(R.id.xlistview_imgtwo);
                        a = listAds.get(1);
                        String imgtwo = a.getImgsrc();
                        String tex = a.getTitle();
                        Logs.e("tex>>>>"+tex);
                        mTextView.setText(tex);
                        Logs.e("imgtwo>>>>"+imgtwo);
                        Glide.with(MainActivity.this).load(imgtwo).into(imageViewtwo);//对于直接从网络取数
                        break;
                    case 2:
                        imageViewthree = (ImageView)view3.findViewById(R.id.xlistview_imgthree);
                        a = listAds.get(2);
                        String imgthree = a.getImgsrc();
                        String texThree = a.getTitle();
                        mTextView.setText(texThree);
                        Logs.e("texThree>>>>"+texThree);
                        Logs.e("imgthree>>>>"+imgthree);
                        Glide.with(MainActivity.this).load(imgthree).into(imageViewthree);//对于直接从网络取数据的图片使用第三方包,
                        break;
                }
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });



    }

    public void onRefresh() {
        Logs.e("onRefresh");
        pageNo = 0;
        getDataLists(pageNo);
        mListView.stopRefresh();
    }

    @Override
    public void onLoadMore() {
        ++pageNo;
        if (pageNo > mTotalPageCount) {
            pageNo = mTotalPageCount;
            mListView.stopLoadMore();
            Toast.makeText(this, "已加载到最后一页", Toast.LENGTH_SHORT).show();
            return;
        }
        Logs.e("pageNo>>>"+pageNo);
        getDataLists(pageNo);

    }
    public void getDataLists(int pageNo) {
        String baseUrl = "http://c.m.163.com/nc/article/headline/"+ news_type_id +"/"+pageNo*pageSize+ "-"  +pageSize+ ".html";
        connectionUtil.asyncConnect(baseUrl, ConnectionUtil.Mothod.GET, new ConnectionUtil.HttpConnectionInterface() {

            public void excute(String cont) {
                if (cont == null) {
                    Toast.makeText(MainActivity.this, "请求出错!", Toast.LENGTH_SHORT).show();
                    return;
                }
                setViewpage(cont);

                Logs.e("content :" + cont);
                mListView.stopLoadMore();
                mListView.stopRefresh();
                mListView.setRefreshTime(simpleDateFormat.format(new Date(System.currentTimeMillis())));

                Gson gson = new Gson();
                Content conten = gson.fromJson(cont, Content.class);
                mTotalPageCount = 5;
                ArrayList<news> list = conten.getT1348647909107();
                mPagerAdapter.addDataList(list);


            }

        });

    }
    public void setViewpage(String content){
        JSONObject jsonObject = null;
        try {
            jsonObject = new JSONObject(content);
            JSONArray jsonObj = jsonObject.getJSONArray("T1348647909107");
            length = jsonObj.length();
            JSONObject jsonObjItemads = jsonObj.getJSONObject(0);
            ads= jsonObjItemads.getJSONArray("ads");
            int len = ads.length();
            Logs.e("ads>>>>"+ads);
            Logs.e("len>>>>"+len);
            for(int g = 0;g<len;g++) {
                JSONObject jsonObjItem = jsonObj.getJSONObject(g);
                String imgsrc = jsonObjItem.getString("imgsrc");
                String tex = jsonObjItem.getString("title");
                Logs.e("imgsrc>>>>" + imgsrc);
                Ads a = new Ads();
                a.setImgsrc(imgsrc);
                a.setTitle(tex);
                listAds.add(a);


            }

        } catch (JSONException e) {
            e.printStackTrace();
        }
        imageViewone = (ImageView) view1.findViewById(R.id.xlistview_imgone);
        a = listAds.get(0);
        String img = a.getImgsrc();
        String tex = a.getTitle();
        mTextView.setText(tex);
        Logs.e("img>>>>"+img);
        Glide.with(MainActivity.this).load(img).into(imageViewone);//对于从网络取数据的图片使用第三方包,还可以缓存

    }



    class MyPagerAdapter extends BaseAdapter {
        List<news> list = new ArrayList<>();
        LayoutInflater layoutInflater;
        public MyPagerAdapter(Context context){
            this.layoutInflater = LayoutInflater.from(context);
        }
        public void SetDatalist(List<news> list){
            this.list = list;
            notifyDataSetChanged();
        }
        public void addDataList(List<news> list){
            this.list.addAll(list);
            notifyDataSetChanged();
        }
        public int getCount() {
            return list.size();
        }

        @Override
        public Object getItem(int i) {
            return list.get(i);
        }

        @Override
        public long getItemId(int i) {
            return i;
        }

        @Override
        public View getView(int i, View view, ViewGroup viewGroup) {
            HoldView holdView;
            if(view == null){
                view = layoutInflater.inflate(R.layout.activity_item_layout,null);
                ImageView imageView = (ImageView) view.findViewById(R.id.item_img);
                TextView title = (TextView) view.findViewById(R.id.item_title);
                TextView content = (TextView) view.findViewById(R.id.item_content);

                holdView = new HoldView();
                holdView.pic = imageView;
                holdView.title = title;
                holdView.content = content;
                view.setTag(holdView);
            }
            holdView = (HoldView) view.getTag();
            news n = (news) getItem(i);
            String title = n.getTitle();
            String content = n.getDigest();
            String img = n.getImgsrc();

            holdView.title.setText(title);
            holdView.content.setText(content);
            Glide.with(MainActivity.this).load(img).into(holdView.pic);//对于直接从网络取数据的图片使用第三方包,还可以缓存
            return view;
        }
    }
    public class HoldView{
        ImageView pic;
        TextView title;
        TextView content;
    }

    public class ViewAdapter extends PagerAdapter {
        List<View> list = new ArrayList<>();

        public ViewAdapter(List<View> list) {
            this.list = list;
        }

        public int getCount() {
            return list.size();
        }

        @Override
        public boolean isViewFromObject(View view, Object object) {
            return view == object;
        }

        public Object instantiateItem(ViewGroup container, int position) {
            View view = list.get(position);
            container.addView(view);
            return view;
        }

        public void destroyItem(ViewGroup container, int position, Object object) {
            View view = list.get(position);
            container.removeView(view);
        }
    }

}
==============================
对于网络的数据转化成对象的相应类
public class Content {

    public ArrayList<news> T1348647909107;

    public ArrayList<news> getT1348647909107() {
        return T1348647909107;
    }

    public void setT1348647909107(ArrayList<news> t1348647909107) {
        T1348647909107 = t1348647909107;
    }
}
========
public class news {
    String title;
    String imgsrc;
    String digest;
    ArrayList<Ads> ads;

    public ArrayList<Ads> getAds() {
        return ads;
    }

    public void setAds(ArrayList<Ads> ads) {
        this.ads = ads;
    }

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    public String getImgsrc() {
        return imgsrc;
    }

    public void setImgsrc(String imgsrc) {
        this.imgsrc = imgsrc;
    }

    public String getDigest() {
        return digest;
    }

    public void setDigest(String digest) {
        this.digest = digest;
    }
}
=======
public class Ads {
    String title;
    String imgsrc;

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    public String getImgsrc() {
        return imgsrc;
    }

    public void setImgsrc(String imgsrc) {
        this.imgsrc = imgsrc;
    }
}
====================================
自定义封装的工具类,实现异步联网取数据
 Created by scxh on 2016/7/28.
 */
public class ConnectionUtil {
    public static final String STRING_CACHE_NAME = "com.example.scxh.myapp.Utils";
    private Context mContext;
    private static boolean isCache = true;
    public enum Mothod {
        GET,POST
    }
    public enum Cache {
        TRUE,FALSE
    }
    public ConnectionUtil(Context context){
        mContext = context;
    }
    public interface HttpConnectionInterface {
        void excute(String content) throws JSONException;
    }

    /**
     * 无参无缓存请求
     *
     * @param httpUrl
     * @param method
     * @param httpConnectionInterface
     */
    public void asyncConnect(final String httpUrl, final Mothod method, final HttpConnectionInterface httpConnectionInterface) {
        asyncConnect(httpUrl, null, method, Cache.FALSE, httpConnectionInterface);
    }

    /**
     * 无参有缓存
     *
     * @param httpUrl
     * @param method
     * @param httpConnectionInterface
     */
    public void asyncConnect(final String httpUrl, final Mothod method, Cache isCache, final HttpConnectionInterface httpConnectionInterface) {
        asyncConnect(httpUrl, null, method, isCache, httpConnectionInterface);
    }

    /**
     * 有参无缓存
     *
     * @param httpUrl
     * @param paramtMap
     * @param method
     * @param httpConnectionInterface
     */
    public void asyncConnect(final String httpUrl, final HashMap<String, String> paramtMap, final Mothod method, final HttpConnectionInterface httpConnectionInterface) {
        asyncConnect(httpUrl, paramtMap, method, Cache.FALSE, httpConnectionInterface);
    }

    /**
     * 有参有缓存请求
     * 异步联网获取Http响应字符串数据
     *
     * @param httpUrl
     * @param
     * @param method
     * @param httpConnectionInterface
     */
    public void asyncConnect(final String httpUrl, final HashMap<String,String> paramMap, final ConnectionUtil.Mothod method, final Cache isCache,
                             final ConnectionUtil.HttpConnectionInterface httpConnectionInterface){
        new AsyncTask<String,Void,String>(){
            @Override
            protected String doInBackground(String... strings) {
                String Urls = strings[0];
                return doHttpConnection(Urls,paramMap,method,isCache);
            }
            protected void onPostExecute(String content){
                try {
                    httpConnectionInterface.excute(content);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        }.execute(httpUrl);
    }
    public String doHttpConnection(String httpUrl, HashMap<String,String> paramMap, ConnectionUtil.Mothod mothod,Cache isCache){
        if(mothod == Mothod.GET){
            if(paramMap != null){
                String paramUrl = "?";
                paramUrl = doParameterHttp(paramUrl,paramMap);
                httpUrl = httpUrl + paramUrl;
            }
            return doGetPostHttp(httpUrl,paramMap,mothod,isCache);
        }else {
            return doGetPostHttp(httpUrl,paramMap,mothod,isCache);
        }
    }
    public String doParameterHttp(String httpUrl,HashMap<String,String> paramMap){
        for(String key:paramMap.keySet()){
            String value = paramMap.get(key);
            httpUrl = httpUrl + key + "=" + value + "&";
        }
        httpUrl = httpUrl.substring(0,httpUrl.length()-1);
        return httpUrl;
    }
    public String doGetPostHttp(String httpUrl,HashMap<String,String> paramMap,Mothod mothod,Cache isCache){
        String message = "";
        HttpURLConnection httpURLConnection = null;
        try {
            URL url = new URL(httpUrl);
            Logs.e("httpUrl>>>"+httpUrl);
            httpURLConnection = (HttpURLConnection) url.openConnection();
            if(mothod == Mothod.GET){
                httpURLConnection.setRequestMethod("GET");
            }else {
                httpURLConnection.setRequestMethod("POST");
            }
           httpURLConnection.setConnectTimeout(5000);//连接超时时间
            httpURLConnection.setReadTimeout(5000); //读数据超时
            httpURLConnection.connect();

            if(mothod == Mothod.POST){
                // post请求的参数
                if(paramMap != null){
                    String data = doParameterHttp("",paramMap);//userName=admin&passWord=123456
                    // 获得一个输出流,向服务器写数据,默认情况下,系统不允许向服务器输出内容
                    OutputStream outputStream = httpURLConnection.getOutputStream();
                    outputStream.write(data.getBytes());
                    outputStream.flush();
                    outputStream.close();
                }
            }

            int code = httpURLConnection.getResponseCode();
            Logs.e("code>>>>"+code);
            if(code == HttpURLConnection.HTTP_OK){
                InputStream inputStream = httpURLConnection.getInputStream();
                message = readInput(inputStream);
                if(isCache == Cache.TRUE){
                    mContext.getSharedPreferences(STRING_CACHE_NAME,Context.MODE_PRIVATE).edit().putString(httpUrl,message).commit();
                }
            }

        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
            String cacheContent = mContext.getSharedPreferences(STRING_CACHE_NAME,Context.MODE_PRIVATE).getString(httpUrl,null);
            return cacheContent;
        }finally {
            httpURLConnection.disconnect();
        }
        return message;
    }
    /**
     * 输入流转字符串
     *
     * @param is
     * @return
     */
    public String readInput(InputStream is) {
        Reader reader = new InputStreamReader(is);  //字节转字符流
        BufferedReader br = new BufferedReader(reader); //字符缓存流

        StringBuilder sb = new StringBuilder();
        String line = null;
        try {
            while ((line = br.readLine()) != null) {
                sb.append(line);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                br.close();
                reader.close();
                is.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        return sb.toString();
    }

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值