PullToRefreshListView第三方的自定义listview用起来很方便,但是有时候我们需要为这个listview添加头,由于PullToRefreshListView没有.addHeaderView方法
这时候添加头,就有点犯难了。其实加头只需要一句简单的代码就行
我们为第三方的PullToRefresh添加头部的方法
由于PullToRefreshListView没有直接添加头布局的方法,所以我们需要用refreshListView.getRefreshableView()把refreshListView一:在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); } } }
<?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>
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; } }