1. 程式人生 > >android viewpager+fragment 避免預載入,快取

android viewpager+fragment 避免預載入,快取

一、需求是這樣的:滑動到哪一頁就在家一頁的資料,避免預載入

二、由於使用setOffScreenLimit無效

解決辦法:

<span style="color:#ff6666;">注意:setUserVisibleHint,使用這個方法來完成切換到哪一頁才載入哪一頁</span>

/**
 *
 * 
 * @author Administrator
 * 
 */
public class GestateKnowledgeBabyTabFragment extends TabBaseFragment implements LmbRequestCallBack {
	/** tab對應的幫的資料來源 */
	private GestateBabyDataItem babyDataItem;
	/** tab對應幫分類Id */
	private int babyTabId;

	/** 快取當前fragment顯示的view,用以當銷燬view但fragment沒銷燬時的回覆 */
	private View cacheFragmentView;
	
	/** 當前fragment是否是可見的 */
	private boolean isFragmentVisible;
	/** 是否已經載入了view,若已經載入了,不會再執行 */
	private boolean isPrepared;

	/**
	 * 
	 * @Description :
	 * @author:zhongwr
	 * @param :babyTabId tab對應的id,不能為空
	 * @param :categoryBangList 如果不為空則資料已經載入過,不用再次請求,如果為空,表示資料沒請求過,則請求網路獲取資料
	 * @return :void
	 */
	public static GestateKnowledgeBabyTabFragment newInstance(int babyTabId, GestateBabyDataItem babyDataItem) {
		GestateKnowledgeBabyTabFragment bangFragment = new GestateKnowledgeBabyTabFragment();
		Bundle argsBundle = new Bundle();
		argsBundle.putInt("babyTabId", babyTabId);
		argsBundle.putSerializable("babyDataItem", babyDataItem);
		bangFragment.setArguments(argsBundle);
		return bangFragment;
	}

	/**
	 * isVisibleToUser:true:表示該UI可以被當前使用者可見;false:表示不可見 是在oncreateView之前執行
	 *
	 *<span style="color:#ff0000;"> 執行順序,用於預載入時,不會執行,第二次執行可見時,由於不會執行oncreateView,所以用此來載入第二次獲取 setUserVisibleHint false--setUserVisibleHint
	 * true--onAttach--onCreate--onCreateView--onActivityCreated--onResume()</span>
	 */
	@Override
	public void setUserVisibleHint(boolean isVisibleToUser) {
		super.setUserVisibleHint(isVisibleToUser);
		// 直接使用isVisibleToUser不準確
		isFragmentVisible = getUserVisibleHint();
		// 第一次載入fragment(由於是viewpager可能是預載入,導致isFragmentVisible=false不可見)並執行此方法時,
		// mactivity==null,當滑動選中,此時activity已經賦值,並且isFragmentVisible=true,再次執行這方法時不會執行oncreateView
		if (null != activity && isFragmentVisible && !isPrepared) {
			onCreateContentView(LayoutInflater.from(activity), null);
		}
	}

	@Override
	public View onCreateViewComplete(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
		Logcat.dLog("isFragmentVisible = " + isFragmentVisible);
		Logcat.dLog("babyTabId = " + babyTabId);
		if (null == cacheFragmentView && isFragmentVisible) {
			isPrepared = true;
			View view = cacheFragmentView = inflater.inflate(R.layout.gestate_baby_knowledge_fragment, null);
			activity = getActivity();
			initView(view);
			initListener();
			initData();
		}
		return cacheFragmentView;
	}

	private void initView(View view) {
		
	}

	/**
	 * 
	 * @description 更新資料
	 * @author zhongwr
	 * @update 2015-11-28 下午6:17:49
	 */
	private void updateViewData(GestateBabyDataItem babyDataItem) {
		if (null != babyDataItem) {
			setClickToReloadGone();
			
			if (null != babyDataItem.bbchange_data && !Tools.isEmpty(babyDataItem.bbchange_data.title)) {
				llBabyChangeParent.setVisibility(View.VISIBLE);
				tvBabyChangeContent.setText(babyDataItem.bbchange_data.text);
				tvBabyChangeTitle.setText(babyDataItem.bbchange_data.title);
			} else {
				llBabyChangeParent.setVisibility(View.GONE);
			}
			// 營養提醒
			if (null != babyDataItem.nutrition_data && !Tools.isEmpty(babyDataItem.nutrition_data.title)) {
				llNutritionParent.setVisibility(View.VISIBLE);
				tvNutritionContent.setText(babyDataItem.nutrition_data.text);
				tvNutritionTitle.setText(babyDataItem.nutrition_data.title);
			} else {
				llNutritionParent.setVisibility(View.GONE);
			}
			
			if (null != babyDataItem.early_data && !Tools.isEmpty(babyDataItem.early_data.title)) {
				llEarlyParent.setVisibility(View.VISIBLE);
				tvEarlyContent.setText(Html.fromHtml(babyDataItem.early_data.text));
				tvEarlyTitle.setText(babyDataItem.early_data.title);
				setViewOnClickListener(llEarlyParent, babyDataItem.early_data.id);
			} else {
				llEarlyParent.setVisibility(View.GONE);
			}
			
			if (null != babyDataItem.month_data && !Tools.isEmpty(babyDataItem.month_data.title)) {
				llConfinementParent.setVisibility(View.VISIBLE);
				tvConfinementTitle.setText(babyDataItem.month_data.title);
				tvConfinementContentTitle.setText(babyDataItem.month_data.small_title);
				tvConfinementContent.setText(Html.fromHtml(babyDataItem.month_data.text));
				imageLoader.displayImage(babyDataItem.month_data.pic, ivConfinementHeadPic, options565);
				setViewOnClickListener(llConfinementParent, babyDataItem.month_data.id);
			} else {
				llConfinementParent.setVisibility(View.GONE);
			}
			// 推薦閱讀
			if (null != babyDataItem.tuijian_data && !Tools.isEmpty(babyDataItem.tuijian_data.title)) {
				llRecommendedParent.setVisibility(View.VISIBLE);
				tvRecommendedTitle.setText(babyDataItem.tuijian_data.title);
				tvRecommendedContentTitle.setText(babyDataItem.tuijian_data.small_title);
				tvRecommendedContent.setText(Html.fromHtml(babyDataItem.tuijian_data.text));
				setBigImageView(babyDataItem.tuijian_data.pic, ivRecommendedPic);
				setViewOnClickListener(llRecommendedParent, babyDataItem.tuijian_data.id);
			} else {
				llRecommendedParent.setVisibility(View.GONE);
			}
			
			if (null != babyDataItem.expert_data && !Tools.isEmpty(babyDataItem.expert_data.title)) {
				llExpertParent.setVisibility(View.VISIBLE);
				tvExpertTitle.setText(babyDataItem.expert_data.title);
				tvExpertContentTitle.setText(babyDataItem.expert_data.small_title);
				tvExpertContent.setText(babyDataItem.expert_data.text);
				imageLoader.displayImage(babyDataItem.expert_data.pic, ivExpertHeadPic, options565);
				setViewOnClickListener(llExpertParent, babyDataItem.expert_data.id);
			} else {
				llExpertParent.setVisibility(View.GONE);
			}
			
			if (null != babyDataItem.expert_video_data && !Tools.isEmpty(babyDataItem.expert_video_data.title)) {
				llVideoParent.setVisibility(View.VISIBLE);
				tvVideoTitle.setText(babyDataItem.expert_video_data.title);
				tvVideoContent.setText(babyDataItem.expert_video_data.small_title);
				setBigImageView(babyDataItem.expert_video_data.pic, ivVideoPic);
				setViewOnClickListener(ivVideoPlay, babyDataItem.expert_video_data.id);
			} else {
				llVideoParent.setVisibility(View.GONE);
			}
			addTagView(babyDataItem.tag_data, flowLayoutTag);
		} else {
			setLoadDataEmpty();
		}
	}

	/***
	 * 
	 * @description 
	 * @author zhongwr
	 * @update 2015-11-30 下午6:09:53
	 */
	private void setViewOnClickListener(View view, final String id) {
		view.setTag(id);
		view.setOnClickListener(clickViewJumpListener);
	}

	
	private OnClickListener clickViewJumpListener = new OnClickListener() {

		@Override
		public void onClick(View v) {
			String id = (String) v.getTag();
			
		}
	};

	/**
	 * 
	 * @description 設定tag標籤
	 * @author zhongwr
	 * @update 2015-11-12 下午6:18:07
	 */
	private void addTagView(GestateBabyTagContainerItem containerItem, FlowLayout flowLayoutTag) {
		if (null == containerItem || Tools.isEmpty(containerItem.title) || Tools.isListEmpty(containerItem.list)) {
			llTagParent.setVisibility(View.GONE);
			return;
		}
		List<GestateBabyTagItem> tagList = containerItem.list;
		flowLayoutTag.removeAllViews();
		llTagParent.setVisibility(View.VISIBLE);
		tvTagTitle.setText(containerItem.title);
		TextView bt = null;
		int padding = Tools.dip2px(activity, 12);
		GestateBabyTagItem tagItem;
		for (int i = 0; i < tagList.size(); i++) {
			tagItem = tagList.get(i);
			bt = new TextView(activity);
			bt.setText(tagItem.small_title != null ? tagItem.small_title : "未知");
			bt.setTextColor(getResources().getColor(R.color.red1));
			bt.setGravity(Gravity.CENTER);
			bt.setBackgroundResource(R.drawable.preg_tag_bg);
			bt.setTextSize(13);
			bt.setPadding(padding, 0, padding, 0);
			bt.setTag(tagItem);
			final String tagId = tagItem.id;
			final String title = tagItem.small_title;
			bt.setOnClickListener(new View.OnClickListener() {

				@Override
				public void onClick(View v) {
					KnowledgeLabelDetailActivity.startKnowledgeLabelDetailAct(activity, tagId, title, "1", null);
				}
			});

			flowLayoutTag.addView(bt);
		}
	}

	private void initListener() {
		setReloadListener(new Reload() {// 出錯重新載入
			@Override
			public void OnReloadClick(View view) {
				requestBabyKnowledgeData();
			}
		});
	}

	private void initData() {
		Bundle argsBundle = getArguments();
		if (null != argsBundle) {
			babyTabId = argsBundle.getInt("babyTabId", 1);
			babyDataItem = (GestateBabyDataItem) argsBundle.getSerializable("babyDataItem");
		}
		if (null == babyDataItem) {
			requestBabyKnowledgeData();
		} else {
			updateViewData(babyDataItem);
		}
	}

	

}

/**
 * 各類tab通用一個Basefragment : 比如 各類tab: 功能: 出錯機制處理
 * 
 * @author Administrator
 * 
 */
public abstract class TabBaseFragment extends BaseFragment {
	public ClickScreenToReload clickToReload;
	private FrameLayout mViewContainer;

	@Override
	public void onAttach(Activity activity) {
		super.onAttach(activity);
		this.activity = activity;
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
		if (null == mViewContainer) {
			View view = inflater.inflate(R.layout.mam_base_main, null);
			mViewContainer = (FrameLayout) view.findViewById(R.id.base_container);
		}
		onCreateContentView(inflater, savedInstanceState);
		return mViewContainer;
	}

	public void onCreateContentView(LayoutInflater inflater, Bundle savedInstanceState) {
		if (null != mViewContainer) {
			mViewContainer.removeAllViews();
			RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.MATCH_PARENT,
					RelativeLayout.LayoutParams.MATCH_PARENT);
			clickToReload = new ClickScreenToReload(activity);
			clickToReload.setVisibility(View.GONE);
			View viewContent = onCreateViewComplete(inflater, mViewContainer, savedInstanceState);
			if (null != viewContent) {
				mViewContainer.addView(viewContent, lp);
			}
			mViewContainer.addView(clickToReload, lp);
		}
	}

	@Override
	public void onDestroyView() {
		super.onDestroyView();
		ViewGroup parent = (ViewGroup) mViewContainer.getParent();
		if (null != parent) {// 必須先清除父佈局中的child,否則會報錯“當前父佈局已經有了一個child,不能再新增”
			mViewContainer.removeAllViewsInLayout();
			parent.removeView(mViewContainer);
		}
	}

	/***
	 * 
	 * @description 建立view
	 * @author zhongwr
	 * @update 2015-11-4 下午5:27:36
	 */
	public abstract View onCreateViewComplete(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState);

	/**
	 * 
	 * @description 設定網路不可見,點選重新載入
	 * @author zhongwr
	 * @update 2015-11-4 下午5:07:12
	 */
	protected void setReloadVisiable() {
		clickToReload.setVisibility(View.VISIBLE);
		clickToReload.setloadfail();
	}

	/**
	 * 
	 * @description 設定載入資料為空
	 * @author zhongwr
	 * @update 2015-11-4 下午5:07:12
	 */
	protected void setLoadDataEmpty() {
		clickToReload.setVisibility(View.VISIBLE);
		clickToReload.setloadEmpty();
	}

	/**
	 * 
	 * @description 設定正在載入
	 * @author zhongwr
	 * @update 2015-11-4 下午5:08:29
	 */
	protected void setLoadingVisiable() {
		clickToReload.setVisibility(View.VISIBLE);
		clickToReload.setLoading();
	}

	/**
	 * 
	 * @description 隱藏這個出錯介面
	 * @author zhongwr
	 * @update 2015-11-4 下午5:09:24
	 */
	protected void setClickToReloadGone() {
		clickToReload.setVisibility(View.GONE);
	}

	/**
	 * 
	 * @description 重新載入的監聽器
	 * @author zhongwr
	 * @update 2015-11-4 下午5:32:44
	 */
	protected void setReloadListener(Reload reloadListener) {
		clickToReload.setReloadClick(reloadListener);
	}

	/** 螢幕的三分之一 */
	private int screenWidthThirdOne = Tools.getScreenSize(activity).x / 3;

	/**
	 * 
	 * @description 適配圖片大圖:圖片佈局除了間距顯示寬度充滿整個螢幕
	 * @author zhongwr
	 * @update 2015-11-13 上午11:32:08
	 */
	protected void setBigImageView(String picUrl, final ImageView ivPic) {
		imageLoader.displayImage(picUrl, ivPic, options565, new SimpleImageLoadingListener() {
			@Override
			public void onLoadingComplete(String imageUri, final View view, final Bitmap loadedImage) {
				if (null != loadedImage) {// 設定成背景,清除src否則重疊
					ivPic.post(new Runnable() {
						@Override
						public void run() {
							int ivMeasureWidth = ivPic.getMeasuredWidth();
							LayoutParams params = ivPic.getLayoutParams();
							int bmWidth = loadedImage.getWidth();
							if (bmWidth < screenWidthThirdOne) {// 處理小圖
								params.height = LayoutParams.WRAP_CONTENT;
								params.width = bmWidth;
							} else if (ivMeasureWidth > 0) {
								// 按原圖的比例縮放
								params.height = ivMeasureWidth * loadedImage.getHeight() / bmWidth;
								params.width = ivMeasureWidth;
							}
							ivPic.setBackgroundDrawable(null);
							ivPic.setImageDrawable(new BitmapDrawable(loadedImage));
						}
					});
				} else {
					ivPic.setImageDrawable(null);// 設定成背景,清除src否則重疊
					ivPic.setBackgroundResource(R.drawable.default_user_head);
				}
			}

			@Override
			public void onLoadingFailed(String imageUri, View view, FailReason failReason) {
				ivPic.setImageDrawable(null);// 設定成背景,清除src否則重疊
				ivPic.setBackgroundResource(R.drawable.default_user_head);
			}
		});
	}
}