引子
最近在做應用內存優化,首要考慮優化的就是首頁推薦位的圖片。
上圖Tab頁是通過ViewPager+Fragment實現的,推薦頁使用了Scrollview可以往下滾動
因此推薦頁有大量的圖片,占用了大量的內存,需要做如下優化
優化項
1.進入推薦頁時,只加載Scrollview中可見的圖片
2.離開推薦頁時,釋放Scrollview中不可見的圖片
3.點擊圖片進入詳情頁后,釋放全部圖片
4.Scrollview滾動時只加載可見的圖片
技術點
1.如何判斷Fragment是否對用戶可見
最容易想到的就是通過生命周期函數
onPause()
和onResume()
來判斷,但是在此viewpager中切換fragment,卻未觸發這兩個生命周期函數。因為viewpager會默認加載當前頁的前后頁,而且還可通過setOffscreenPageLimit
來設置默認加載多頁。那有什么辦法知道Fragment是否對用戶可見呢?有的,具體分幾種情況
- ViewPager+Fragment
因為Fragment懶加載機制的原因,切換時Fragment并未銷毀,不會觸發onPause()
,因此需要用setUserVisibleHint()
來判斷
/**
* Set a hint to the system about whether this fragment's UI is currently visible
* to the user. This hint defaults to true and is persistent across fragment instance
* state save and restore.
*
* <p>An app may set this to false to indicate that the fragment's UI is
* scrolled out of visibility or is otherwise not directly visible to the user.
* This may be used by the system to prioritize operations such as fragment lifecycle updates
* or loader ordering behavior.</p>
*
* <p><strong>Note:</strong> This method may be called outside of the fragment lifecycle.
* and thus has no ordering guarantees with regard to fragment lifecycle method calls.</p>
*
* @param isVisibleToUser true if this fragment's UI is currently visible to the user (default),
* false if it is not.
*/
public void setUserVisibleHint(boolean isVisibleToUser) {
if (!mUserVisibleHint && isVisibleToUser && mState < STARTED
&& mFragmentManager != null && isAdded()) {
mFragmentManager.performPendingDeferredStart(this);
}
mUserVisibleHint = isVisibleToUser;
mDeferStart = mState < STARTED && !isVisibleToUser;
}
ViewPager初始化時不會觸發setUserVisibleHint()
,只會在切換Fragment時
- Activity+Fragment
xml引入fragment,或者通過addFragment
、replaceFragment
,直接判斷onPause()
和onResume()
即可 - FragmentManger show() hide()
fragment沒有被銷毀,雖然不可見,但是不會觸發onPause
,需要用onHiddenChanged()
來判斷
@Override
public void onHiddenChanged(boolean hidden) {
super.onHiddenChanged(hidden);
if(hidden){
//TODO now visible to user
} else {
//TODO now invisible to user
}
}
2.如何判斷View是否可見
判斷View是否在屏幕中可見,可使用如下函數
/**
* 判斷視圖是否顯示在屏幕上
* @param context
* @param view
* @return
*/
public static boolean checkIsVisible(Context context, View view) {
int screenWidth = getScreenMetrics(context).x;
int screenHeight = getScreenMetrics(context).y;
Rect rect = new Rect(0, 0, screenWidth, screenHeight);
int[] location = new int[2];
view.getLocationInWindow(location);
if (view.getLocalVisibleRect(rect)) {
return true;
} else {
//view已不在屏幕可見區域;
return false;
}
}
3.如何判斷View是否在ScrollView中可見
判斷View是否在ScrollView中可見,可使用如下函數
private boolean isVisibleInScrollView(ScrollView scroll, View view) {
Rect bounds = new Rect();
view.getHitRect(bounds);
Rect scrollBounds = new Rect(scroll.getScrollX(), scroll.getScrollY(),
scroll.getScrollX() + scroll.getWidth(), scroll.getScrollY() + scroll.getHeight());
if (Rect.intersects(scrollBounds, bounds)) {
return true;
} else {
return false;
}
}
4.如何控制圖片加載
控制圖片加載我們不能直接使用
View.setVisibility(View.VISIBLE|VIew.GONE)
,否則會視圖需要重新渲染,引起操作時的卡頓。
我們可以通過發送dispatchDisplayHint(int hint)
,然后在View中處理onDisplayHint(int hint)
來控制圖片加載
/**
* Dispatch a hint about whether this view is displayed. For instance, when
* a View moves out of the screen, it might receives a display hint indicating
* the view is not displayed. Applications should not <em>rely</em> on this hint
* as there is no guarantee that they will receive one.
*
* @param hint A hint about whether or not this view is displayed:
* {@link #VISIBLE} or {@link #INVISIBLE}.
*/
public void dispatchDisplayHint(int hint) {
onDisplayHint(hint);
}
/**
* Gives this view a hint about whether is displayed or not. For instance, when
* a View moves out of the screen, it might receives a display hint indicating
* the view is not displayed. Applications should not <em>rely</em> on this hint
* as there is no guarantee that they will receive one.
*
* @param hint A hint about whether or not this view is displayed:
* {@link #VISIBLE} or {@link #INVISIBLE}.
*/
protected void onDisplayHint(int hint) {
}
具體優化工作
1.進入推薦頁時,只加載Scrollview中可見的圖片
@Override
public void onResume() {
super.onResume();
Logger.getLogger().d("onResume");
if (getUserVisibleHint()) {
setScrollVisibleView();
}
}
private void setScrollVisibleView() {
if (mRecommendContainerLayout == null) {
return;
}
for (int i = 0; i < mRecommendContainerLayout.getChildCount(); i++) {
final RecommendContainer recommendContainer = (RecommendContainer) mRecommendContainerLayout.getChildAt(i);
if (isVisibleInScrollView(mScrollView, recommendContainer)) {
Logger.getLogger().d("setScrollVisibleView v=%s,vi=%s", recommendContainer, View.VISIBLE);
recommendContainer.dispatchDisplayHint(View.VISIBLE);
} else {
//Logger.getLogger().d("setScrollVisibleView v=%s,vi=%s", recommendContainer, View.GONE);
//recommendContainer.dispatchDisplayHint(View.INVISIBLE);
}
}
}
2.離開推薦頁時,釋放Scrollview中不可見的圖片
@Override
public void setUserVisibleHint(final boolean isVisibleToUser) {
super.setUserVisibleHint(isVisibleToUser);
Logger.getLogger().d("setUserVisibleHint, isVisibleToUser=%s", isVisibleToUser);
if (mRecommendContainerLayout == null) {
return;
}
for (int i = 0; i < mRecommendContainerLayout.getChildCount(); i++) {
final RecommendContainer recommendContainer = (RecommendContainer) mRecommendContainerLayout.getChildAt(i);
final boolean isVisibleInScrollView = isVisibleInScrollView(mScrollView, recommendContainer);
Logger.getLogger().d("setUserVisibleHint v=%s,isVisibleToUser=%s,isVisibleInScrollView=%s," +
"checkIsVisible=%s", recommendContainer.getId(), isVisibleToUser, isVisibleInScrollView,
ViewUtils.checkIsVisible(getContext(), recommendContainer));
recommendContainer.dispatchDisplayHint( isVisibleInScrollView ? View.VISIBLE :
View.GONE);
}
}
3.點擊圖片進入詳情頁后,釋放全部圖片
@Override
public void onPause() {
super.onPause();
Logger.getLogger().d("onPause");
hideAllViews();
}
private void hideAllViews() {
if (mRecommendContainerLayout == null) {
return;
}
for (int i = 0; i < mRecommendContainerLayout.getChildCount(); i++) {
final RecommendContainer recommendContainer = (RecommendContainer) mRecommendContainerLayout.getChildAt(i);
Logger.getLogger().d("hideAllViews v=%s,vi=%s", recommendContainer, View.GONE);
mRecommendContainerLayout.postDelayed(new Runnable() {
@Override
public void run() {
recommendContainer.dispatchDisplayHint(View.INVISIBLE);
}
}, 300);
}
}
4.Scrollview滾動時只加載可見的圖片
@Override
public void onScrollChanged(ScrollView scrollView, int x, int y, int oldx, int oldy) {
if (Math.abs(oldy - y) > 50) {
//Logger.getLogger().d("recommendFragment setScrollVisibleView");
setScrollVisibleView();
}
}
參考
關于fragment到底是否可見的問題
如何判斷Fragment是否對用戶可見
Android: how to check if a View inside of ScrollView is visible?