实现Fragment数据的缓加载,即滑动到当前页再加载数据

来源:互联网 发布:淘宝德国代购有假货吗 编辑:程序博客网 时间:2024/05/01 06:57

1.

/**

重写的Fragment,每个Fragment继承自LazyFragment 

/


package com.tf.mixReader.fragment;



import android.support.v4.app.Fragment;


/**
 * Author: msdx (645079761@qq.com)
 * Time: 14-7-17 下午5:46
 */
public abstract class LazyFragment extends Fragment {
    protected boolean isVisible;
    /**
     * 在这里实现Fragment数据的缓加载.
     * @param isVisibleToUser
     */
    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        if(getUserVisibleHint()) {
            isVisible = true;
            onVisible();
        } else {
            isVisible = false;
            onInvisible();
        }
    }
 
    protected void onVisible(){
        lazyLoad();
    }
 
    protected abstract void lazyLoad();
 
    protected void onInvisible(){}

}

------------------------------------------------------------------------------------------------------------------------------------------------

2.例子:ZhihuFragment


/*
 * Copyright (C) 2013 Andreas Stuetz <andreas.stuetz@gmail.com>
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */


package com.tf.mixReader.fragment;


import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;


import zrc.widget.SimpleFooter;
import zrc.widget.SimpleHeader;
import zrc.widget.ZrcListView;
import zrc.widget.ZrcListView.OnItemClickListener;
import zrc.widget.ZrcListView.OnStartListener;


import com.duowan.mobile.netroid.Listener;
import com.duowan.mobile.netroid.NetroidError;
import com.duowan.mobile.netroid.Request;
import com.duowan.mobile.netroid.request.StringRequest;
import com.google.gson.Gson;
import com.tf.mixReader.R;
import com.tf.mixReader.activity.NewsDetails4ZhiHuActivity;
import com.tf.mixReader.activity.NewsDetails4DouBanActivity;
import com.tf.mixReader.adapter.DouBanListViewAdapter;
import com.tf.mixReader.adapter.ZhihuListViewAdapter;
import com.tf.mixReader.application.Netroid;
import com.tf.mixReader.model.News;
import com.tf.mixReader.model.zhihu.zhihuBean;
import com.tf.mixReader.model.zhihu.zhihuImage;
import com.tf.mixReader.model.zhihu.zhihuStory;
import com.tf.mixReader.tools.BaseTool;
import com.tf.mixReader.tools.PullParseService;


import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;


public class ZhihuFragment extends LazyFragment {


private View public_view;


// private SwipeRefreshLayout swipeLayout;


/**
* ListView适配器
*/
private ZhihuListViewAdapter adapter;


/**
* ListView
*/
private ZrcListView listView;
List<News> listNews;


// 标志位,标志已经初始化完成。
private boolean isPrepared;
private boolean autoRefresh = true;

Gson gson;
private String historyDate;
private List<zhihuStory> sotryList,historyList;
public static ZhihuFragment newInstance() {
ZhihuFragment f = new ZhihuFragment();


return f;
}


@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
gson = new Gson();
}


@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {


if (public_view == null) {
public_view = inflater.inflate(R.layout.zhihu_layout, null);


listView = (ZrcListView) public_view.findViewById(R.id.listview);
sotryList = new ArrayList<zhihuStory>();
historyList = new ArrayList<zhihuStory>();
// 设置默认偏移量,主要用于实现透明标题栏功能。(可选)
// float density = getResources().getDisplayMetrics().density;
// listView.setFirstTopOffset((int) (50 * density));


// 设置下拉刷新的样式(可选,但如果没有Header则无法下拉刷新)
SimpleHeader header = new SimpleHeader(public_view.getContext());
header.setTextColor(getResources().getColor(R.color.zhihu_color));
header.setCircleColor(getResources().getColor(R.color.zhihu_color));
listView.setHeadable(header);


// 设置加载更多的样式(可选)
SimpleFooter footer = new SimpleFooter(public_view.getContext());
footer.setCircleColor(getResources().getColor(R.color.zhihu_color));
listView.setFootable(footer);


// 设置列表项出现动画(可选)
listView.setItemAnimForTopIn(R.anim.topitem_in);
listView.setItemAnimForBottomIn(R.anim.bottomitem_in);


// 下拉刷新事件回调(可选)
listView.setOnRefreshStartListener(new OnStartListener() {
@Override
public void onStart() {
Log.e("回調", "refresh");
refresh();
}
});


// 加载更多事件回调(可选)
listView.setOnLoadMoreStartListener(new OnStartListener() {
@Override
public void onStart() {

loadMore();
}
});


listView.setOnItemClickListener(new OnItemClickListener() {


@Override
public void onItemClick(ZrcListView parent, View view,
int position, long id) {

listView.setBackgroundColor(getResources().getColor(R.color.whitesmoke));
// TODO Auto-generated method stub
Bundle bundle = new Bundle();
Intent intent = new Intent();
/*
* bundle.putString("DESCRIPTION", listNews.get(position)
* .getDescription());
*/
bundle.putString("DESCRIPTION", adapter.getItem(position)
.getShare_url());
intent.putExtras(bundle);
intent.setClass(getActivity(),
NewsDetails4ZhiHuActivity.class);
startActivity(intent);
getActivity().overridePendingTransition(R.anim.slide_in_left, R.anim.slide_out_right);
}
});
}


// 缓存的rootView需要判断是否已经被加过parent,
// 如果有parent需要从parent删除,要不然会发生这个rootview已经有parent的错误。
ViewGroup parent = (ViewGroup) public_view.getParent();
if (parent != null) {
parent.removeView(public_view);
}


Log.e("onCreateView", "onCreateView");

isPrepared = true;
lazyLoad();

return public_view;
}


private void refresh() {
Log.e("times", "refresh");
if(adapter!=null){
Log.e("adapter", "---------clear");
adapter.clear();
//first_day_sotryList.clear();
}
Log.e("currentdate", BaseTool.getCurrentDate());
getDataList(BaseTool.getCurrentDate());

}


private void loadMore() {

handler.postDelayed(new Runnable() {
 
 @Override public void run() {
 Log.e("historyDate", historyDate);
 StringBuilder sb=new StringBuilder(historyDate);
 sb.insert(4,"-");
 sb.insert(7,"-");
 
 Log.e("sb", sb.toString());
 
 historyDate=BaseTool.getSpecifiedDayBefore(sb.toString());
 Log.e("historyDate", historyDate);
 getHistoryDataList(historyDate);
 
} }, 1 * 1000);


/*
* handler.postDelayed(new Runnable() {

* @Override public void run() { pageId++; if(pageId<names.length){
* for(String name:names[pageId]){ msgs.add(name); }
* adapter.notifyDataSetChanged(); listView.setLoadMoreSuccess(); }else{
* listView.stopLoadMore(); } } }, 2 * 1000);
*/
}



private void getDataList(String date) {
if (sotryList!=null&&sotryList.size() != 0){

sotryList.clear();
}


historyDate=date;
StringRequest request = new StringRequest(Request.Method.GET,
"http://news.at.zhihu.com/api/3/news/before/"+date,
new Listener<String>() {


public void onNetworking() {
// Toast.makeText(Inbox_Avtivity.this, "请求网络时获取该方法",
// Toast.LENGTH_LONG).show();


}


public void onUsedCache() {
// Toast.makeText(Inbox_Avtivity.this, "请求缓存时获取该方法",
// Toast.LENGTH_LONG).show();


}


@Override
public void onSuccess( String response) {

zhihuBean zhihubean = gson.fromJson(response,
zhihuBean.class);
sotryList = zhihubean.getStories();

adapter = new ZhihuListViewAdapter(public_view
.getContext(), sotryList);
listView.setAdapter(adapter);

listView.setRefreshSuccess("加载成功"); // 通知加载成功
listView.startLoadMore(); // 开启LoadingMore功能

}


@Override
public void onError(NetroidError error) {


listView.setRefreshFail("加载失败"); // 通知加载成功


}


});


// 忽略请求的硬盘缓存,直接执行Http操作
request.setForceUpdate(true);
// Http操作成功后保存进缓存的过期时间
request.setCacheExpireTime(TimeUnit.MINUTES, 60);
Netroid.mRequestQueue.add(request);
}



private void getHistoryDataList(String date) {
if (historyList!=null&&historyList.size() != 0){

historyList.clear();
}


historyDate=date;
StringRequest request = new StringRequest(Request.Method.GET,
"http://news.at.zhihu.com/api/3/news/before/"+date,
new Listener<String>() {


public void onNetworking() {
// Toast.makeText(Inbox_Avtivity.this, "请求网络时获取该方法",
// Toast.LENGTH_LONG).show();


}


public void onUsedCache() {
// Toast.makeText(Inbox_Avtivity.this, "请求缓存时获取该方法",
// Toast.LENGTH_LONG).show();


}


@Override
public void onSuccess(final String response) {

zhihuBean zhihubean = gson.fromJson(response,
zhihuBean.class);
historyList = zhihubean.getStories();

adapter.addAll(historyList);
adapter.notifyDataSetChanged();

listView.setLoadMoreSuccess();



}


@Override
public void onError(NetroidError error) {


listView.stopLoadMore();


}


});


// 忽略请求的硬盘缓存,直接执行Http操作
request.setForceUpdate(true);
// Http操作成功后保存进缓存的过期时间
request.setCacheExpireTime(TimeUnit.MINUTES, 60);
Netroid.mRequestQueue.add(request);
}


/*
* private void getDataList() {

* StringRequest request = new StringRequest(Request.Method.GET,
* "http://zhihurss.jd-app.com/dailyrss", new Listener<String>() {

* public void onNetworking() { // Toast.makeText(Inbox_Avtivity.this,
* "请求网络时获取该方法", // Toast.LENGTH_LONG).show();

* }

* public void onUsedCache() { // Toast.makeText(Inbox_Avtivity.this,
* "请求缓存时获取该方法", // Toast.LENGTH_LONG).show();

* }

* @Override public void onSuccess(final String response) { // TODO
* Auto-generated method stub // Toast.makeText(Inbox_Avtivity.this, //
* "JSONArray length : " + response.length(), // 2000).show(); //
* Log.e("douban", response);

* try { Log.e("douban", "1");

* new Thread() {

* public void run() {

* try { listNews = PullParseService .URLReadXmlByPull(response, "zhihu");
* Message message = new Message(); message.what = 1;
* handler.sendMessage(message); } catch (Exception e) { // TODO
* Auto-generated catch block e.printStackTrace(); }

* }

* }.start();

* listView.setRefreshSuccess("加载成功"); // 通知加载成功 listView.startLoadMore();
* // 开启LoadingMore功能

* } catch (Exception e) { // TODO Auto-generated catch block
* e.printStackTrace(); }

* }

* @Override public void onError(NetroidError error) {

* listView.setRefreshSuccess("加载失败"); // 通知加载成功

* }

* });

* // 忽略请求的硬盘缓存,直接执行Http操作 request.setForceUpdate(true); //
* Http操作成功后保存进缓存的过期时间 request.setCacheExpireTime(TimeUnit.MINUTES, 20);
* Netroid.mRequestQueue.add(request); }
*/


private Handler handler = new Handler() {
@Override
// 当有消息发送出来的时候就执行Handler的这个方法
public void handleMessage(Message msg) {
super.handleMessage(msg);
// 处理UI
switch (msg.what) {


case 1:
handler.post(pullXMLUI);
break;


}


}
};


Runnable pullXMLUI = new Runnable() {
@Override
public void run() {
pullXMLUI();


}


};


private void pullXMLUI() {


/*
* adapter = new ZhihuListViewAdapter(public_view.getContext(),
* listNews); listView.setAdapter(adapter);
* adapter.notifyDataSetChanged();
*/


}


@Override
protected void lazyLoad() {

Log.e("isPrepared:", isPrepared+"");
Log.e("isVisible:", isVisible+"");
Log.e("autoRefresh:", autoRefresh+"");

if (!isPrepared || !isVisible) {
return;
}
// 填充各控件的数据
if (autoRefresh == true) {
Log.e("主動", "refresh");
listView.refresh(); // 主动下拉刷新
autoRefresh = false;
}


}

}



0 0
原创粉丝点击