Listview,頂部加viewpager,並且帶有上拉刷新和下拉分頁功能的展示

   上次發了一篇文章是listview頭部帶有viewpager,viewpager是網絡獲取,並且帶有輪播功能,總感覺有些地方還是不完美,
這次,在上一次的基礎上,將listview,和viewpager中的所有的數據全部都從網絡上獲取,而且添加了一些佈局美化,希望這篇文章能夠幫到大家,
這次我會簡單的在代碼塊中對一些相應的方法進行描述,這樣大家就可以看的明瞭些了。
</pre><pre name="code" class="java">本篇文章使用的控件總結:
1,listview,顯示列表
2,viewpager,顯示輪播
3,swipRefresh用於下拉刷新
4,cardView,顯示佈局立體感
效果如圖:
關於適配器等一些列的簡單部分我就不貼代碼了,
<img src="https://img-blog.csdn.net/20161105213315322?watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQv/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/gravity/Center" alt="" />
</pre><pre name="code" class="java">
下邊是代碼部分:
<pre name="code" class="java">package com.yz.myviewpagertest;

import android.graphics.Color;
import android.os.Handler;
import android.os.Message;

import android.os.Bundle;
import android.support.v4.view.ViewPager;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.app.AppCompatActivity;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AbsListView;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.squareup.okhttp.OkHttpClient;
import com.squareup.picasso.Picasso;
import com.yz.myviewpagertest.helper.JsonHelper;
import com.yz.myviewpagertest.helper.OkHttpClientHelper;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

public class MainActivity extends AppCompatActivity {
    //url地址用於獲取網絡數據
    public String PATH = "http://dailyapi.ibaozou.com/api/v31/documents/latest?timestamp=";
    //聲明需要的控件和對應的適配器;
    private ViewPager viewPager_main;
    private MyPagerAdatper adapter;
    private LinearLayout lin;
    private ListView list_view_main;
    private MyList_adapter listv_adapter;

    //用於後期修改url拼接使用
    private String timetemp = "";
    //接收頭部的bean數據,listview需要的databean數據,和盛放圖片的圖片集合,和盛放“點”的集合
    private List<BaozouBean.TopStoriesBean> top_stories = new ArrayList<>();
    private List<ImageView> imageV_list = new ArrayList<>();
    private List<ImageView> dot_list = new ArrayList<>();
    List<BaozouBean.DataBean> dataBean_mList = new ArrayList<>();
    //初始化下標;
    private int position = 0;
    //判斷是第一次加載,是下拉刷新,是到達底部
    private boolean isEnd = false;
    private boolean isDownRefresh = false;
    private boolean isforstload = true;
    //用於下拉刷新的控件
    SwipeRefreshLayout swipeRefreshLayout;
    //用於自動輪播的定時器
    private Handler handle = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 1:
                    //重置點,的初始圖片
                    reset();
                    dot_list.get(position).setImageResource(R.mipmap.social_page_indicator_selected);
                    viewPager_main.setCurrentItem(position);
                    position++;
                    if (position >= dot_list.size()) {
                        position = 0;
                    }
                    //定時器
                    handle.sendEmptyMessageDelayed(1, 2000);

                    break;
            }


        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        //初始化view
        initView();
        //加載數據
        LoadData();
        //設置監聽器
        MyListeners();
    }

    private void reset() {
        for (ImageView dot : dot_list
                ) {
            dot.setImageResource(R.mipmap.social_page_indicator);
        }

    }

    private void MyListeners() {
        list_view_main.setOnScrollListener(new AbsListView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(AbsListView view, int scrollState) {
                if (isEnd) {

                    LoadData();

                }


            }

            @Override
            public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
               //判斷是否在尾部
                isEnd = firstVisibleItem + visibleItemCount == totalItemCount;

            }
        });

//刷新監聽
        swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                isDownRefresh = true;
                LoadData();


            }
        });


    }
//加載數據的方法
    private void LoadData() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    String json_str = OkHttpClientHelper.getStringFromURL(MainActivity.this, getSubPath(timetemp, PATH), "path_photo");
                    BaozouBean baozouBean = new Gson().fromJson(json_str, new TypeToken<BaozouBean>() {
                    }.getType());
                    //得到通過解析的頭部數據
                    top_stories = baozouBean.getTop_stories();
                    //得到listview中的未抽取數據
                    final List<BaozouBean.DataBean> dataBeanList = baozouBean.getData();
                    timetemp = baozouBean.getTimestamp() + "";
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            //將數據源進行填充,因爲分頁加載時此處如果爲空,監聽器iterater會報空,要加分頁判斷;
                            if (top_stories != null && isforstload) {
                                imageV_list.clear();
                                dot_list.clear();
                                for (BaozouBean.TopStoriesBean top_bean : top_stories
                                        ) {
                                    //填充圖片
                                    ImageView imageV = new ImageView(MainActivity.this);
                                    Picasso.with(MainActivity.this).load(top_bean.getImage()).into(imageV);

                                    imageV_list.add(imageV);
                                    //填充點的個數;
                                    ImageView image_dot = new ImageView(MainActivity.this);
                                    image_dot.setImageResource(R.mipmap.social_page_indicator);
                                    image_dot.setClickable(true);
                                    lin.addView(image_dot);
                                    dot_list.add(image_dot);

                                }

                                if (isforstload) {
                                    handle.sendEmptyMessage(1);
                                    isforstload = false;
                                }
                                //刷新適配器
                                adapter.notifyDataSetChanged();


                            }
                            //底部判斷,從新加載適配器
                            if (isEnd) {
                                if (dataBeanList != null) {

                                    listv_adapter.reloadListView(dataBeanList, false);

                                }
                                
                            }
                            
                            if (isDownRefresh) {
                                listv_adapter.reloadListView(dataBeanList, true);
                                isDownRefresh = false;
                                swipeRefreshLayout.setRefreshing(false);
                            }

                        }
                    });


                } catch (IOException e) {
                    e.printStackTrace();
                }

            }
        }).start();


    }

    private String getSubPath(String timetemp, String path) {
        if (timetemp == "") {
            return path;
        }
        if (isDownRefresh) {
            return path;
        } else {
            return path + timetemp + "&";
        }


    }

    private void initView() {
        //頭部
        View head_view = LayoutInflater.from(this).inflate(R.layout.viewpager_headforlistview, null);
        lin = (LinearLayout) head_view.findViewById(R.id.lin);
        viewPager_main = (ViewPager) head_view.findViewById(R.id.viewpager_main);
        adapter = new MyPagerAdatper(top_stories, this, imageV_list);
        viewPager_main.setAdapter(adapter);
        //listview,
        list_view_main = (ListView) findViewById(R.id.listview_main);
        list_view_main.addHeaderView(head_view);
        //添加適配器
        listv_adapter = new MyList_adapter(this, dataBean_mList);
        list_view_main.setAdapter(listv_adapter);
        //上拉刷新
        swipeRefreshLayout = (SwipeRefreshLayout) findViewById(R.id.swipRefreshlayouut);
        swipeRefreshLayout.setColorSchemeColors(Color.BLUE, Color.GREEN, Color.RED);


    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        OkHttpClientHelper.cancelCall("path_photo");

    }
}



//下面是封裝的工具類,需要的可以用,不需要的可以忽略掉此處,<pre name="code" class="java"> BaseAdapterHelper
</pre><pre name="code" class="java">

<pre name="code" class="java">package com.yz.myviewpagertest.helper;

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

import java.util.List;

public abstract class BaseAdapterHelper<T> extends BaseAdapter {
    public Context mContext = null;
    public List<T> mList = null;
    public LayoutInflater mInflater = null;

    public BaseAdapterHelper(Context context, List<T> list) {
        this.mContext = context;
        this.mList = list;
        mInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    }

    @Override
    public int getCount() {
        return mList.size();
    }

    @Override
    public T getItem(int position) {
        return mList.get(position);
    }

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

    public void reloadListView(List<T> data, boolean isClear) {
        if (isClear) {
            mList.clear();
        }
        mList.addAll(data);
        notifyDataSetChanged();
    }

    public void clearAll() {
        mList.clear();
        notifyDataSetChanged();
    }

    //根據list的position刪除單條數據
    public void removeItem(int position) {
        mList.remove(position);
        notifyDataSetChanged();
    }

    //刪除多條數據
    public void removeItems(List<T> _list) {
        mList.removeAll(_list);
        notifyDataSetChanged();
    }


    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        return getItemView(position, convertView, parent);
    }

    public abstract View getItemView(int position, View convertView, ViewGroup parent);

}



//這個是okhttp的封裝okhttphelper
<pre name="code" class="java">  * 作用:實現網絡訪問文件,將獲取到的數據存在字符串中
     *
     * @param urlString :訪問網絡的url地址
     * @return String
     */
    public static String getStringFromURL(Context context, String urlString, Object tag) throws
            IOException {
        ResponseBody body = getOkHttpClientUtils(context).buildResponseBody(urlString, tag);
        if (body != null) {
            return body.string();
        }
        return null;
    }
</pre><pre name="code" class="java">
//MainActivity的佈局,使用了cardview
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.yz.myviewpagertest.MainActivity">

    <android.support.v4.widget.SwipeRefreshLayout
        android:id="@+id/swipRefreshlayouut"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

        <ListView
            android:id="@+id/listview_main"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:divider="@null">

        </ListView>


    </android.support.v4.widget.SwipeRefreshLayout>


</RelativeLayout>
</pre><pre name="code" class="java">
//item佈局
<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    app:cardBackgroundColor="#80cbc4"
    app:cardCornerRadius="10dp"
    app:cardPreventCornerOverlap="true"
    app:cardUseCompatPadding="true">

    <LinearLayout
        android:padding="5dp"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:gravity="center_vertical"
        android:orientation="horizontal">

        <ImageView
            android:id="@+id/image_thumbnails"
            android:layout_width="60dp"
            android:layout_height="60dp"
            android:src="@mipmap/ic_launcher" />

        <LinearLayout
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:orientation="vertical">

            <TextView
                android:id="@+id/text_title"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_marginLeft="20dp"
                android:layout_marginTop="5dp"
                android:layout_toRightOf="@+id/image_thumbnails"
                android:text="title"
                android:textSize="18sp" />

            <TextView
                android:id="@+id/text_content"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_below="@+id/text_title"
                android:layout_marginLeft="10dp"
                android:layout_marginTop="5dp"
                android:layout_toRightOf="@+id/image_thumbnails"
                android:text="content" />


        </LinearLayout>


    </LinearLayout>
</android.support.v7.widget.CardView>
</pre><pre name="code" class="java">//listivew適配器
<pre name="code" class="java">package com.yz.myviewpagertest;

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

import com.squareup.picasso.Picasso;
import com.yz.myviewpagertest.helper.BaseAdapterHelper;

import java.util.List;

/**
 * Created by Administrator on 2016/11/5.
 */
public class MyList_adapter extends BaseAdapterHelper<BaozouBean.DataBean> {
    public MyList_adapter(Context context, List<BaozouBean.DataBean> mList) {
        super(context, mList);
    }


    @Override
    public View getItemView(int position, View convertView, ViewGroup parent) {
        ViewHolder vh = null;
        if (convertView == null) {
            convertView = LayoutInflater.from(mContext).inflate(R.layout.item_listview, parent, false);
            vh=new ViewHolder(convertView);
            convertView.setTag(vh);
        } else {
            vh = (ViewHolder) convertView.getTag();
        }
        BaozouBean.DataBean dataBean = mList.get(position);
        vh.text_title.setText(dataBean.getAuthor_name());
        vh.text_content.setText(dataBean.getTitle());
        Picasso.with(mContext).load(dataBean.getThumbnail()).into(vh.imge_Icon);


        return convertView;
    }

    class ViewHolder {
        private TextView text_title, text_content;
        private ImageView imge_Icon;

        public ViewHolder(View conv) {
            text_title = (TextView) conv.findViewById(R.id.text_title);
            text_content = (TextView) conv.findViewById(R.id.text_content);
            imge_Icon = (ImageView) conv.findViewById(R.id.image_thumbnails);

        }

    }
}

還有一些簡單的東西,比如item的適配器,viewpager的適配器,這些代碼就不貼了,價值性不高,如果有需要完整代碼的可以私聊我,或者留言,我發給大家。




</pre><pre name="code" class="java">
</pre><pre name="code" class="java">
</pre><pre name="code" class="java">
</pre><pre name="code" class="java">
發佈了39 篇原創文章 · 獲贊 14 · 訪問量 4萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章