Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
 Android教程網 >> Android技術 >> Android開發 >> 關於android開發 >> viewpager和fragment預加載的解決,viewpagerfragment

viewpager和fragment預加載的解決,viewpagerfragment

編輯:關於android開發

viewpager和fragment預加載的解決,viewpagerfragment


在使用Viewpager和fragment處理中會出現預加載的問題,最近看別人的代碼,終於找到了一個很好的處理方法

能有效的解決預加載的問題,在fragment都繼承一個重寫setUserVisibleHint類的基類

如圖是效果圖

      

其實在是一個fragment中,用Viewpager和fragment再展示3個界面

不過如果你是在activity中實現Viewpager和fragment的結合不要這麼麻煩  這句代碼就夠了 viewPager.setOffscreenPageLimit(3)不用重寫什麼MyLazyFragment 了;

如下是主要代碼

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;
        }
        
    }
    
}

 

  1. 上一頁:
  2. 下一頁:
熱門文章
閱讀排行版
Copyright © Android教程網 All Rights Reserved