在使用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; } } }