viewpager和fragment预加载的解决
在使用Viewpager和fragment处理中会出现预加载的问题,最近看别人的代码,终于找到了一个很好的处理方法
能有效的解决预加载的问题,在fragment都继承一个重写setUserVisibleHint类的基类
如图是效果图
其实在是一个fragment中,用Viewpager和fragment再展示3个界面
不过如果你是在activity中实现Viewpager和fragment的结合不要这么麻烦 这句代码就够了 viewPager.setOffscreenPageLimit(3)不用重写什么MyLazyFragment 了;但是用viewPager.setOffscreenPageLimit(3)实际上是一次性把几个ViewPager都加载出来以后就不加载了;用懒加载的处理,实际上是滑到第二个界面时再加载二个的数据。
如下是主要代码
最后写的程序代码连接:http://download.csdn.net/detail/qq_29774291/9620872
package com.ithello.suibianxie.activity.notice; import android.support.v4.app.Fragment; public abstract class MyLazyFragment 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 abstract void onVisible(); protected abstract void onInvisible();
}
其中第一个fragment的处理方法和其他的不同
package com.ithello.suibianxie.activity.fragment; import org.xutils.x;
import org.xutils.common.Callback;
import org.xutils.http.RequestParams; import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView; import com.ithello.suibianxie.R;
import com.ithello.suibianxie.activity.notice.MyLazyFragment;
import com.ithello.suibianxie.common.GlobalData;
import com.ithello.suibianxie.util.Constant; public class VideoListFragment extends MyLazyFragment{ private boolean isPrepared;
private boolean isFirstLoad = false;
private TextView tView;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// TODO Auto-generated method stub
//return inflater.inflate(R.layout.videolistfragment, container, false);
View view = inflater.inflate(R.layout.videolistfragment, null);
isPrepared = true;
initView(view);
System.out.println("1");
firstLoad();
return view;
} private void initView(View view) {
// TODO Auto-generated method stub
tView=(TextView)view.findViewById(R.id.tv_videofragment);
} @Override
protected void onVisible() {
// TODO Auto-generated method stub
Log.d("jiejie", "11 isPreparen:" + isPrepared + ", isVisible" + isVisible);
if(!isPrepared || !isVisible){
return;
}
if(!isFirstLoad){
isFirstLoad = true;
//firstLoad();
}
} private void firstLoad() {
// TODO Auto-generated method stub
requestDates();
} private void requestDates() {
// TODO Auto-generated method stub
RequestParams params = new RequestParams(Constant.findAppArticleList_url);
params.addBodyParameter("rc", GlobalData.getGlobalData().getRc());
params.addBodyParameter("page", 1+"");
params.addBodyParameter("rows", 10 +"");
params.addBodyParameter("appOS", "android");
x.http().get(params, new Callback.CommonCallback<String>() { @Override
public void onCancelled(CancelledException arg0) {
// TODO Auto-generated method stub } @Override
public void onError(Throwable arg0, boolean arg1) {
// TODO Auto-generated method stub } @Override
public void onFinished() {
// TODO Auto-generated method stub } @Override
public void onSuccess(String arg0) {
// TODO Auto-generated method stub
Log.d("jiejie", arg0);
tView.setText(arg0);
}
});
} @Override
protected void onInvisible() {
// TODO Auto-generated method stub } }
package com.ithello.suibianxie.activity.fragment; import java.util.ArrayList;
import java.util.List; import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.xutils.x;
import org.xutils.common.Callback;
import org.xutils.http.RequestParams; import android.os.Bundle;
import android.text.format.DateUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListView; import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshBase.OnLastItemVisibleListener;
import com.handmark.pulltorefresh.library.PullToRefreshBase.OnRefreshListener;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
import com.ithello.suibianxie.R;
import com.ithello.suibianxie.activity.notice.MyLazyFragment;
import com.ithello.suibianxie.adapter.ArticleAdapter;
import com.ithello.suibianxie.common.GlobalData;
import com.ithello.suibianxie.entity.Article;
import com.ithello.suibianxie.util.Constant; public class ArticleFragment extends MyLazyFragment {
// private List<Article> list = new ArrayList<Article>();
private List<JSONObject> list = new ArrayList<JSONObject>();
private PullToRefreshListView mPullToRefreshListView;
private ListView listView;
private ArticleAdapter mAdapter; private int page = 0;
private int rows = 10;
private int total = 0;
// private String urlString
// ="http://111.39.245.155:9527/dtbt/findAppArticleList.action"; // 标志位,标志已经初始化完成
private boolean isPrepared;
private boolean isFirstLoad = false; @Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// TODO Auto-generated method stub
// return super.onCreateView(inflater, container, savedInstanceState);
// return inflater.inflate(R.layout.articlefragment, container, false);
View view = inflater.inflate(R.layout.articlefragment, null);
initListView(view);
isPrepared = true;
System.out.println("2");
return view;
} @Override
protected void onVisible() {
// TODO Auto-generated method stub
Log.d("jiejie", "22 isPrepared:" + isPrepared + ", isVisible" + isVisible);
if (!isPrepared || !isVisible) {
return;
}
if (!isFirstLoad) {
isFirstLoad = true;
firstLoad();
} } @Override
protected void onInvisible() {
// TODO Auto-generated method stub
} private void firstLoad() {
// TODO Auto-generated method stub
// mAdapter.notifyDataSetChanged();
// list.clear();
page = 1;
requestDate(page);
} private void initListView(View view) {
// TODO Auto-generated method stub
listView = (ListView)view.findViewById(R.id.art_listview); } /**
* 进行网络的请求
*
* @param page2
*/
protected void requestDate(int page2) {
// TODO Auto-generated method stub
RequestParams params = new RequestParams(
Constant.findAppArticleList_url);
params.addBodyParameter("rc", GlobalData.getGlobalData().getRc());
params.addBodyParameter("page", page2 + "");
params.addBodyParameter("rows", rows + "");
params.addBodyParameter("appOS", "android");
x.http().get(params, new Callback.CommonCallback<String>() { @Override
public void onCancelled(CancelledException arg0) {
// TODO Auto-generated method stub } @Override
public void onError(Throwable arg0, boolean arg1) {
// TODO Auto-generated method stub } @Override
public void onFinished() {
// TODO Auto-generated method stub } @Override
public void onSuccess(String arg0) {
// TODO Auto-generated method stub
System.out.println(arg0);
Log.d("jiejie", arg0);
if(arg0 != null){
try {
JSONObject object= new JSONObject(arg0);
JSONArray array = object.getJSONArray("rows");
JSONObject dataJsonObject;
for(int i = 0 ; i<array.length();i++){
dataJsonObject =array.getJSONObject(i);
list.add(dataJsonObject);
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
mAdapter = new ArticleAdapter(getActivity(), list);
listView.setAdapter(mAdapter);
}
}
});
} }
package com.ithello.suibianxie.activity.fragment; import org.xutils.x;
import org.xutils.common.Callback;
import org.xutils.http.RequestParams; import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView; import com.ithello.suibianxie.R;
import com.ithello.suibianxie.activity.notice.MyLazyFragment;
import com.ithello.suibianxie.common.GlobalData;
import com.ithello.suibianxie.util.Constant; public class NoticeFragment extends MyLazyFragment{
private boolean isPrepared;
private boolean isFirstLoad = false;
private TextView tView ;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// TODO Auto-generated method stub
//return inflater.inflate(R.layout.noticefragment, container, false);
View view = inflater.inflate(R.layout.noticefragment, null);
isPrepared = true;
initView(view);
System.out.println("3");
return view;
}
private void initView(View view) {
// TODO Auto-generated method stub
tView = (TextView)view.findViewById(R.id.tv_notice);
}
@Override
protected void onVisible() {
// TODO Auto-generated method stub
Log.d("jiejie", "33 isPreparen" + isPrepared + ", isVisibletrue" + isVisible);
if(!isPrepared || !isVisible){
return;
}
if(!isFirstLoad){
isFirstLoad = true;
firstLoad();
}
} @Override
protected void onInvisible() {
// TODO Auto-generated method stub }
private void firstLoad() {
// TODO Auto-generated method stub
stHttoop();
}
private void stHttoop() {
// TODO Auto-generated method stub
RequestParams params = new RequestParams(Constant.findAppArticleList_url);
params.addBodyParameter("rc", GlobalData.getGlobalData().getRc());
params.addBodyParameter("page", 1+"");
params.addBodyParameter("rows", 10 +"");
params.addBodyParameter("appOS", "android");
x.http().get(params, new Callback.CommonCallback<String>() { @Override
public void onCancelled(CancelledException arg0) {
// TODO Auto-generated method stub } @Override
public void onError(Throwable arg0, boolean arg1) {
// TODO Auto-generated method stub } @Override
public void onFinished() {
// TODO Auto-generated method stub } @Override
public void onSuccess(String arg0) {
// TODO Auto-generated method stub
Log.d("jiejie", arg0);
tView.setText(arg0);
}
});
} }
其中Viewpager和fragment的结合我用的是IndicatorViewPager来实现的
package com.ithello.suibianxie.fragment; import com.ithello.suibianxie.R;
import com.ithello.suibianxie.activity.fragment.ArticleFragment;
import com.ithello.suibianxie.activity.fragment.NoticeFragment;
import com.ithello.suibianxie.activity.fragment.VideoListFragment;
import com.potato.viewpagerindicator.view.indicator.IndicatorViewPager;
import com.potato.viewpagerindicator.view.indicator.adapter.IndicatorFragmentPagerAdapter;
import com.potato.viewpagerindicator.view.indicator.indicator.Indicator;
import com.potato.viewpagerindicator.view.indicator.slidebar.ColorBar;
import com.potato.viewpagerindicator.view.indicator.transition.OnTransitionTextListener; import android.content.res.Resources;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.view.ViewPager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.RelativeLayout;
import android.widget.TextView; /**
* 第三个fragment
* @author zh
*
*/
public class MThreeFragment extends Fragment{
private IndicatorViewPager indicatorViewPager; @Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// TODO Auto-generated method stub
return inflater.inflate(R.layout.mthreefragment, container, false);
}
@Override
public void onActivityCreated(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onActivityCreated(savedInstanceState);
setView();
} private void setView() {
// TODO Auto-generated method stub
Resources res = getResources();
ViewPager viewPager =(ViewPager)getActivity().findViewById(R.id.fragment_training_home_viewPager);
Indicator indicator =(Indicator)getActivity().findViewById(R.id.fragment_training_home_fixedindicatorview);
int color =getResources().getColor(R.color.tab_indicator_daab3c);
indicator.setScrollBar(new ColorBar(getActivity(), color, 2));
float unSelectSize = 14;
float selectSize = unSelectSize * 1.0f;
int selectColor =res.getColor(R.color.tab_title_color_select_daab3c);
int unSelectColor = res.getColor(R.color.tab_title_color_normal_e8d6ab);
indicator.setOnTransitionListener(new OnTransitionTextListener().setColor(selectColor, unSelectColor).setSize(selectSize, unSelectSize));
viewPager.setOffscreenPageLimit(3);
indicatorViewPager = new IndicatorViewPager(indicator, viewPager);
indicatorViewPager.setAdapter(new MyAdapter(getChildFragmentManager()));
} private String[] tabNames ={"视频","文章","通知"}; private class MyAdapter extends IndicatorFragmentPagerAdapter{ public MyAdapter(FragmentManager fragmentManager) {
super(fragmentManager);
// TODO Auto-generated constructor stub
} @Override
public int getCount() {
// TODO Auto-generated method stub
return 3;
} @Override
public Fragment getFragmentForPage(int position) {
// TODO Auto-generated method stub
Bundle bundle = new Bundle();
if(position ==0){
VideoListFragment videoListFragment = new VideoListFragment();
videoListFragment.setArguments(bundle);
return videoListFragment;
}else if (position == 1) {
ArticleFragment articleFragment = new ArticleFragment();
articleFragment.setArguments(bundle);
return articleFragment;
}else if (position ==2) {
NoticeFragment noticeFragment = new NoticeFragment();
noticeFragment.setArguments(bundle);
return noticeFragment;
}
VideoListFragment mainFragment = new VideoListFragment();
mainFragment.setArguments(bundle);
return mainFragment;
} @Override
public View getViewForTab(int position, View convertView, ViewGroup container) {
// TODO Auto-generated method stub
if(convertView == null){
if(position ==0){
convertView = View.inflate(getActivity(), R.layout.title_bae_left, null);
}else if (position ==1) {
convertView = View.inflate(getActivity(), R.layout.title_bar_middle, null);
}else if (position == 2) {
convertView = View.inflate(getActivity(), R.layout.title_bar_right, null);
}
}
RelativeLayout layout = (RelativeLayout)convertView;
TextView tView = (TextView)layout.findViewById(R.id.tv);
tView.setText(tabNames[position]);
return convertView;
} } }
viewpager和fragment预加载的解决的更多相关文章
- IIS初始化设置预加载,解决程序池被回收第一次访问慢问题
问题现象: 部署到IIS上的项目,第一次访问比较慢,有时后空闲一段时间去访问也会很慢,经常隔天访问也会慢.这就是IIS回收导致的问题,IIS回收把程序池的内存释放,网站就相当与重启的状态,被回收后,我 ...
- Android中ViewPager+Fragment取消(禁止)预加载延迟加载(懒加载)问题解决方案
转载请注明出处:http://blog.csdn.net/linglongxin24/article/details/53205878本文出自[DylanAndroid的博客] Android中Vie ...
- 防止ViewPager和Fragment结合使用时候的数据预加载
不知道你们使用ViewPager和Fragment结合的时候发现一个问题没,如果你的每个Fragment都需要请求网络数据,并且你在请求网络数据的时候会加入进度对话框的加载显示效果,当你显示第一个Fr ...
- 关于禁止ViewPager预加载问题【转】
转自:http://blog.csdn.net/qq_21898059/article/details/51453938#comments 我最近上班又遇到一个小难题了,就是如题所述:ViewPage ...
- Fragment懒加载预加载
1. 预加载viewpager.setOffscreenPageLimit(2);,默认是预加载1,可以结合懒加载使用. 如果希望进入viewpager,Fragment只加载一次,再次滑动不需加载( ...
- viewpager处理(三):让viewpager不预加载下一页
有时候viewpager加载页面的时候,我们发现页面的数据量很大,预加载的话会消耗性能,为了节省用户流量和手机性能,所以我们想让viewpager不自动预加载下一页,怎么实现呢? viewpager预 ...
- spine实现预加载(一)
前言 本文实现了spine动画的预加载,解决在战斗等大量加载spine动画的时候出现卡顿现象. 这里使用和修改三个类,直接修改的源码,当然你也可以继承LuaSkeletonAnimation,自己封装 ...
- 巧力避免ViewPager的预加载数据,Tablayout+Fragment+viewPager
问题描述 最近在进行一个项目的开发,其中使用到了Tablayout+Fragment+viewPager来搭建一个基本的框架,从而出现了设置数据适配器的时候,item的位置错乱问题.我打印log日志的 ...
- ViewPager+Fragment取消预加载(延迟加载)(转)
原文:http://www.2cto.com/kf/201501/368954.html 在项目中,都或多或少地使用的Tab布局,所以大都会用到ViewPager+Fragment,但是Fragmen ...
随机推荐
- NSString NSUrl 相互转化
//NSString 转为 NSURL NSString *webStr = @"www.baidu.com"; NSURL *webUrl = [NSURL URLWithStr ...
- Logstash为什么那么慢?—— json序列化
今天跟峡谷金桥聊天,询问起Logstash的性能,金桥提示说Logstash中json的序列化是浪费性能的一方面.于是便有了下面的测试: 第一步,造数据 首先需要造一份数据,数据可以通过logstas ...
- Atitit Server Side Include ssi服务端包含规范 csi esi
Atitit Server Side Include ssi服务端包含规范 csi esi 一.CSI (Client Side Includes) 1 1.1. 客户端包含1 1.2. Ang ...
- 百度面试题 字符串相似度 算法 similar_text 和页面相似度算法
在百度的面试,简直就是花样求虐. 首先在面试官看简历的期间,除了一个自己定义字符串相似度,并且写出求相似度的算法. ...这个确实没听说过,php的similar_text函数也是闻所未闻的.之前看s ...
- css3实现超出文本指定行数(指定文本长度)用省略号代替
测试代码: <!DOCTYPE html> <html> <head> <meta name="viewport" content=&qu ...
- 【原创】NIO框架入门(四):Android与MINA2、Netty4的跨平台UDP双向通信实战
概述 本文演示的是一个Android客户端程序,通过UDP协议与两个典型的NIO框架服务端,实现跨平台双向通信的完整Demo. 当前由于NIO框架的流行,使得开发大并发.高性能的互联网服务端成为可能. ...
- Android入门(六)碎片
原文链接:http://www.orlion.ga/493/ 一.碎片 碎片(Fragment)是一种可以嵌入在活动当中的 UI片段,它能让程序更加合理和充分地利用大屏幕的空间,因而在平板上应用的非常 ...
- Java多线程系列--“基础篇”06之 线程让步
概要 本章,会对Thread中的线程让步方法yield()进行介绍.涉及到的内容包括:1. yield()介绍2. yield()示例3. yield() 与 wait()的比较 转载请注明出处:ht ...
- 栈的存储结构和常见操作(c 语言实现)
俗话说得好,线性表(尤其是链表)是一切数据结构和算法的基础,很多复杂甚至是高级的数据结构和算法,细节处,除去数学和计算机程序基础的知识,大量的都在应用线性表. 一.栈 其实本质还是线性表:限定仅在表尾 ...
- jQuery.noConflict()
转载:http://blog.163.com/mjuxiaom@126/blog/static/13397047120117324320858/ 运行这个函数将变量$的控制权让渡给第一个实现它的那个库 ...