1. 程式人生 > >安卓中PullToRefreshListview新增頭部的方法

安卓中PullToRefreshListview新增頭部的方法

PullToRefreshListView第三方的自定義listview用起來很方便,但是有時候我們需要為這個listview新增頭,由於PullToRefreshListView沒有.addHeaderView方法

這時候新增頭,就有點犯難了。其實加頭只需要一句簡單的程式碼就行

我們為第三方的PullToRefresh新增頭部的方法

由於PullToRefreshListView沒有直接新增頭佈局的方法,所以我們需要用refreshListView.getRefreshableView()把refreshListView
轉化成正常的listview,轉化後的listview才可以新增頭佈局。

private PullToRefreshListView refreshListView;
private ListView listView;
listView = refreshListView.getRefreshableView();
 listView .addHeaderView(headerView);

下面兩個例子分別為activity和fragment中的PullToRefresh新增頭




一:在activity中為PullToRefresh新增頭

package com.huxiu.yd;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;


import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
import com.huxiu.yd.net.GsonRequest;
import com.huxiu.yd.net.NetworkConstants;
import com.huxiu.yd.net.NetworkHelper;
import com.huxiu.yd.net.model.DiscoveryItem;
import com.huxiu.yd.net.responses.DiscoveryListResponse;
import com.huxiu.yd.utils.Utils;
import com.makeramen.roundedimageview.RoundedImageView;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.listener.PauseOnScrollListener;


import java.util.ArrayList;
import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;


import butterknife.ButterKnife;
import butterknife.InjectView;


public class JiFenActivity2 extends BaseActivity
        implements PullToRefreshBase.OnRefreshListener2<ListView>, View.OnClickListener {
    @InjectView(R.id.back)
    ImageView back;
    @InjectView(R.id.title)
    TextView title;
    @InjectView(R.id.right_text)
    TextView rightText;




    FrameLayout qiandao_frame;
    RoundedImageView qiandao_bg;
    LinearLayout qiandao_ok;
    LinearLayout qiandao_no;
    TextView jifen_num;
    @InjectView(R.id.list_out)
    PullToRefreshListView list_out;
    ListView list;




    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_ji_fen2);
        ButterKnife.inject(this);
        View headerView = View.inflate(getApplicationContext(), R.layout.list_mine_header,
                null);
        qiandao_frame = (FrameLayout) headerView.findViewById(R.id.qiandao_frame);
        qiandao_bg = (RoundedImageView) headerView.findViewById(R.id.qiandao_bg);
        qiandao_ok = (LinearLayout) headerView.findViewById(R.id.qiandao_ok);
        qiandao_no = (LinearLayout) headerView.findViewById(R.id.qiandao_no);


        list = list_out.getRefreshableView();
        list.setDividerHeight(0);// 隱藏listview預設的divider
        list.setSelector(android.R.color.transparent);// 隱藏listview預設的selector
        rightText.setVisibility(View.VISIBLE);
        rightText.setText(R.string.shuoming);
        rightText.setTextColor(0xffffffff);
        back.setOnClickListener(this);
        rightText.setOnClickListener(this);
        qiandao_frame.setOnClickListener(this);
        title.setText(R.string.myjifen);
        list.addHeaderView(headerView);
        list_out.setOnRefreshListener(this);
        list_out.setState(PullToRefreshBase.State.INIT_REFRESHING, true);
        PauseOnScrollListener listener = new PauseOnScrollListener(ImageLoader.getInstance(), false,
                true);
        list_out.setOnScrollListener(listener);
        adapter = new MyAdapter();
        list.setAdapter(adapter);


    }


    @Override
    public void onPullDownToRefresh(PullToRefreshBase refreshView) {
        getItems(1);
    }


    @Override
    public void onPullUpToRefresh(PullToRefreshBase refreshView) {
        getItems(currentPage + 1);
    }


    private void refreshComplete() {
        list_out.postDelayed(new Runnable() {
            @Override
            public void run() {
                list_out.onRefreshComplete();
            }
        }, 100);
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        ButterKnife.reset(this);
        NetworkHelper.getInstance().getRequestQueue().cancelAll(this);


    }




    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.qiandao_frame:
                Utils.showToast("點選旋轉動畫");
                break;
            case R.id.back:
                finish();
                break;
            case R.id.right_text:
                Utils.showToast("跳到積分頁面");
                break;
        }
    }




    private int totalPages = 0;
    private int currentPage = 0;
    private List<DiscoveryItem> items = new ArrayList<>();


    private void getItems(final int page) {
        String url = NetworkConstants.ACTION_URL;
        Map<String, String> params = new LinkedHashMap<>();
        params.put("act", "credits_log");
        params.put("page", Integer.toString(page));
        GsonRequest<DiscoveryListResponse> request = new GsonRequest<>(url, Request.Method.POST,
                DiscoveryListResponse.class, true, params, new Response.Listener<DiscoveryListResponse>() {
            @Override
            public void onResponse(DiscoveryListResponse response) {
                if (response.isSuccess()) {
                    if (page == 1 || page == 0) {
                        items.clear();
                    }
                    if (list_out != null) {
                        if (response.page == response.max_page) {
                            list_out.setMode(PullToRefreshBase.Mode.PULL_FROM_START);
                        } else {
                            list_out.setMode(PullToRefreshBase.Mode.BOTH);
                        }
                    }
                    Collections.addAll(items, response.data);
                    adapter.notifyDataSetChanged();
                    currentPage = response.page;
                } else {
                    Utils.showToast(response.msg);
                }
                refreshComplete();
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError volleyError) {
                Utils.showToast(R.string.generic_failure);
                refreshComplete();
            }
        });
        NetworkHelper.getInstance().addToRequestQueue(request);
    }




    private MyAdapter adapter;


    class MyAdapter extends BaseAdapter {


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


        @Override
        public Object getItem(int position) {
            return items.get(position);
        }


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




        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            ViewHolder vh;
            View v = convertView;
            if (v == null) {
                v = getLayoutInflater().inflate(R.layout.item_jifen_list, parent, false);
                vh = new ViewHolder(v);
                v.setTag(vh);
            }
            final DiscoveryItem item = items.get(position);
            vh = (ViewHolder) v.getTag();
            vh.jifen_type.setText(item.message);
            vh.jifen_time.setText(Utils.getDateString(item.create_time));
            vh.jifen_num.setText("+" + item.value);
            return v;
        }
    }


    class ViewHolder {
        @InjectView(R.id.jifen_type)
        TextView jifen_type;


        @InjectView(R.id.jifen_time)
        TextView jifen_time;


        @InjectView(R.id.jifen_num)
        TextView jifen_num;


        ViewHolder(View view) {
            ButterKnife.inject(this, view);
        }
    }
}


貼一下上面activity的佈局檔案
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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:background="@color/white"
              android:orientation="vertical">

    <include
        android:id="@+id/header"
        layout="@layout/header"/>

    <com.handmark.pulltorefresh.library.PullToRefreshListView
        android:id="@+id/list_out"
        xmlns:ptr="http://schemas.android.com/apk/res-auto"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:divider="@null"
        android:footerDividersEnabled="false"
        android:listSelector="@android:color/transparent"
        ptr:ptrHeaderTextColor="@color/gray4"
        ptr:ptrMode="both"
        tools:listitem="@layout/discovery_list_item"/>
</LinearLayout>




二,在fragment中為PullToRefresh新增頭

package com.shitou.googleplay.ui.fragment;


import java.util.ArrayList;


import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;


import android.content.Intent;
import android.os.Handler;
import android.support.v4.view.ViewPager;
import android.text.TextUtils;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.LinearLayout.LayoutParams;
import android.widget.ListView;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshBase.Mode;
import com.handmark.pulltorefresh.library.PullToRefreshBase.OnRefreshListener;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
import com.googleplay.R;
import com.shitou.googleplay.bean.AppInfo;
import com.shitou.googleplay.bean.Home;
import com.shitou.googleplay.http.HttpHelper;
import com.shitou.googleplay.http.Url;
import com.shitou.googleplay.ui.activity.AppDetailActivity;
import com.shitou.googleplay.ui.adapter.HomeAdapter;
import com.shitou.googleplay.ui.adapter.HomePagerAdapter;
import com.shitou.googleplay.util.CommonUtil;
import com.shitou.googleplay.util.JsonUtil;
import com.shitou.googleplay.util.LogUtil;


public class HomeFragment extends BaseFragment {


private PullToRefreshListView refreshListView;
private ViewPager homePager;
private HomeAdapter homeAdapter;
private ArrayList<AppInfo> list = new ArrayList<AppInfo>();
private ListView listView;
private HomePagerAdapter homePagerAdapter;

private Handler handler = new Handler(){
public void handleMessage(android.os.Message msg) {
homePager.setCurrentItem(homePager.getCurrentItem()+1);

handler.sendEmptyMessageDelayed(0, 3000);
};
};


@Override
protected View getSuccessView() {
initRefreshListView();//初始化PullToRefreshListView

initHeaderView();//新增頭部的ViewPager

//設定Adapter
homeAdapter = new HomeAdapter(list);
listView.setAdapter(homeAdapter);



return refreshListView;
}


/**
* 初始化PullToRefreshListView
*/
private void initRefreshListView() {
// 1.初始化refreshListView,並且給它設定重新整理監聽
refreshListView = (PullToRefreshListView) View.inflate(getActivity(),
R.layout.ptr_listview, null);
refreshListView.setMode(Mode.BOTH);// 設定兩邊都可以啦
refreshListView.setOnRefreshListener(new OnRefreshListener<ListView>() {
/**
* 上拉重新整理和下拉載入更多都會執行該方法
* 
* @param refreshView
*/
@Override
public void onRefresh(PullToRefreshBase<ListView> refreshView) {
if (refreshListView.getCurrentMode() == Mode.PULL_FROM_START) {
// 下拉重新整理
CommonUtil.runOnUIThread(new Runnable() {
@Override
public void run() {
refreshListView.onRefreshComplete();// 完成重新整理的方法
}
});
} else {
// 上拉載入更多,應該載入下一頁的資料
contentPage.loadDataAndRefreshPage();
}
}
});
listView = refreshListView.getRefreshableView();
listView.setDividerHeight(0);// 隱藏listview預設的divider
listView.setSelector(android.R.color.transparent);// 隱藏listview預設的selector

//給listView增加item點選事件
listView.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// LogUtil.e(this, "position:"+position);
Intent intent = new Intent(getActivity(),AppDetailActivity.class);
intent.putExtra("packageName",list.get(position-2).getPackageName());
startActivity(intent);
}
});
}
/**
* 初始化headerView
*/
private void initHeaderView(){
View headerView = View.inflate(getActivity(), R.layout.layout_home_pager, null);
homePager = (ViewPager) headerView.findViewById(R.id.homePager);
//1.計算出ViewPager的寬度
float width = getActivity().getWindowManager().getDefaultDisplay().getWidth();
//2.根據圖片的寬高比,計算出對應的高度,寬高比是2.65
float height = width/2.65f;
//3.將計算出來的高度重新賦值給VIewPager的高度
LayoutParams layoutParams = (LayoutParams) homePager.getLayoutParams();
layoutParams.height = (int) height;//重新給佈局引數設定
homePager.setLayoutParams(layoutParams);
// homePager.requestLayout();//也可以這樣寫

listView.addHeaderView(headerView);
}


@Override
protected Object requestData() {
String result = HttpHelper.get(Url.Home + list.size());


final Home home = JsonUtil.parseJsonToBean(result, Home.class);
if (home != null) {
// 更新資料
list.addAll(home.getList());
CommonUtil.runOnUIThread(new Runnable() {
@Override
public void run() {
//由於輪播圖的url資料,只有在載入第一頁的時候才有,
if(home.getPicture()!=null && home.getPicture().size()>0){
//表明是第一頁載入資料,此時是有輪播圖url的資料
homePagerAdapter = new HomePagerAdapter(home.getPicture());
homePager.setAdapter(homePagerAdapter);
//一開始設定選中的是中間的item
homePager.setCurrentItem(home.getPicture().size()*10000);
}

// 更新adapter
homeAdapter.notifyDataSetChanged();


// 完成重新整理
refreshListView.onRefreshComplete();// 完成重新整理的方法
}
});
}


return home;
}

@Override
public void onStart() {
super.onStart();
//傳送延時訊息
handler.sendEmptyMessageDelayed(0, 3000);
}

@Override
public void onStop() {
super.onStop();
//移除訊息
handler.removeCallbacksAndMessages(null);
}



/**
* 使用JSONObject解析json
* 
* @param json
* @return
*/
private Home parseJson(String json) {
if (TextUtils.isEmpty(json))
return null;


Home home = new Home();
try {
JSONObject jsonObject = new JSONObject(json);
// 1.解析picture欄位
ArrayList<String> picture = new ArrayList<String>();
JSONArray pictureArray = jsonObject.getJSONArray("picture");
for (int i = 0; i < pictureArray.length(); i++) {
String string = pictureArray.getString(i);
picture.add(string);
}
home.setPicture(picture);


// 2.解析list欄位
ArrayList<AppInfo> list = new ArrayList<AppInfo>();
JSONArray listArray = jsonObject.getJSONArray("list");
for (int i = 0; i < listArray.length(); i++) {
JSONObject object = listArray.getJSONObject(i);
AppInfo appInfo = new AppInfo();
appInfo.setDes(object.getString("des"));
appInfo.setDownloadUrl(object.getString("downloadUrl"));
appInfo.setIconUrl(object.getString("iconUrl"));
appInfo.setId(object.getInt("id"));
appInfo.setName(object.getString("name"));
appInfo.setPackageName(object.getString("packageName"));
appInfo.setSize(object.getLong("size"));
appInfo.setStars((float) object.getDouble("stars"));


list.add(appInfo);
}
home.setList(list);
} catch (JSONException e) {
e.printStackTrace();
}


return home;
}
}