在使用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预加载的解决的更多相关文章

  1. IIS初始化设置预加载,解决程序池被回收第一次访问慢问题

    问题现象: 部署到IIS上的项目,第一次访问比较慢,有时后空闲一段时间去访问也会很慢,经常隔天访问也会慢.这就是IIS回收导致的问题,IIS回收把程序池的内存释放,网站就相当与重启的状态,被回收后,我 ...

  2. Android中ViewPager+Fragment取消(禁止)预加载延迟加载(懒加载)问题解决方案

    转载请注明出处:http://blog.csdn.net/linglongxin24/article/details/53205878本文出自[DylanAndroid的博客] Android中Vie ...

  3. 防止ViewPager和Fragment结合使用时候的数据预加载

    不知道你们使用ViewPager和Fragment结合的时候发现一个问题没,如果你的每个Fragment都需要请求网络数据,并且你在请求网络数据的时候会加入进度对话框的加载显示效果,当你显示第一个Fr ...

  4. 关于禁止ViewPager预加载问题【转】

    转自:http://blog.csdn.net/qq_21898059/article/details/51453938#comments 我最近上班又遇到一个小难题了,就是如题所述:ViewPage ...

  5. Fragment懒加载预加载

    1. 预加载viewpager.setOffscreenPageLimit(2);,默认是预加载1,可以结合懒加载使用. 如果希望进入viewpager,Fragment只加载一次,再次滑动不需加载( ...

  6. viewpager处理(三):让viewpager不预加载下一页

    有时候viewpager加载页面的时候,我们发现页面的数据量很大,预加载的话会消耗性能,为了节省用户流量和手机性能,所以我们想让viewpager不自动预加载下一页,怎么实现呢? viewpager预 ...

  7. spine实现预加载(一)

    前言 本文实现了spine动画的预加载,解决在战斗等大量加载spine动画的时候出现卡顿现象. 这里使用和修改三个类,直接修改的源码,当然你也可以继承LuaSkeletonAnimation,自己封装 ...

  8. 巧力避免ViewPager的预加载数据,Tablayout+Fragment+viewPager

    问题描述 最近在进行一个项目的开发,其中使用到了Tablayout+Fragment+viewPager来搭建一个基本的框架,从而出现了设置数据适配器的时候,item的位置错乱问题.我打印log日志的 ...

  9. ViewPager+Fragment取消预加载(延迟加载)(转)

    原文:http://www.2cto.com/kf/201501/368954.html 在项目中,都或多或少地使用的Tab布局,所以大都会用到ViewPager+Fragment,但是Fragmen ...

随机推荐

  1. Oracle日期语言修改

    -- value带有两个参数,第一个指下限,第二个指上限,将会生成下限到上限之间的数字,但不包含上限.select ceil(dbms_random.value(1000,9999)) from du ...

  2. EF架构~关于多对多关系表无法更新与插入的问题

    回到目录 在EF里,我们设计模型时,会设计到多对多关系,在EF里会把这种关系会转成两个一对多的关系表,这是比较友好的,因为多对多来说,对于业务本身没什么意思,所以隐藏了,没什么坏处,但对于这个隐藏来说 ...

  3. Model-View-Controller(MVC) is an architectural pattern that frequently used in web applications. Which of the following statement(s) is(are) correct?

    Model-View-Controller(MVC) is an architectural pattern that frequently used in web applications. Whi ...

  4. IDE:Eclipse查看Servlet源码

    一.源码下载 1.打开tomcat官网:http://tomcat.apache.org/    , 点击右侧下载菜单(以tomcat-7为例)进入下载页面:http://tomcat.apache. ...

  5. Android Studio下载及使用教程(转载)

    (一)下载及相关问题解决: Android Studio 下载地址,目前最新可下载地址,尽量使用下载工具. Android Studio正式发布,给Android开发者带来了不小的惊喜.但是下载地址却 ...

  6. binary 和 varbinary 用法

    数据类型 binary(n) 和 varbinary(n) 用于存储二进制数据,n是指字节数量: binary( n ):长度为 n 字节的固定长度二进制数据,其中 n 是从 1 到 8,000 的值 ...

  7. IO流-概览

    一. 抽象类InputStream和OutputStream构成了了IO类的基础 因为面向字节流的对象不便于处理Unicode形式储存的信息,所以从抽象类Reader和Writer中继承出专门用于处理 ...

  8. QQ5.0左侧滑动显示效果

    前三篇为大家介绍了如何实现简单的类QQ5.0左侧的侧滑效果,本篇我将带领大家一起探讨一下如何真正实现QQ5.0左侧的侧滑效果,对于本篇的内容与之前的三篇关联性很强,如果前三篇你已经完全掌握,对于这一篇 ...

  9. c#方法重载,可选参数,命名参数。

    其实这里没什么可说哦,c++的语法大同小异.先看一段代码. class Program { public static void Test(int a) { Console.WriteLine(&qu ...

  10. 15款免费的 HTML5/CSS3 响应式网页模板

    如果你想快速制作出一个优秀的网站,网站模板一定是必不可少的.网页设计师和开发人员也可以从网站模板入手,学习先进的布局方式和编码风格.下面这个列表为大家挑选了15款免费的 HTML5/CSS3 响应式网 ...