美文网首页Fragment
View的可见性与图片加载优化

View的可见性与图片加载优化

作者: 一骑绝尘Louisk | 来源:发表于2017-11-13 18:10 被阅读17次

    引子

    最近在做应用内存优化,首要考虑优化的就是首页推荐位的图片。

    首页.png

    上图Tab页是通过ViewPager+Fragment实现的,推荐页使用了Scrollview可以往下滚动

    首页_滚动.png

    因此推荐页有大量的图片,占用了大量的内存,需要做如下优化

    优化项

    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.

    *

    *

    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.

    *

    *

    Note: This method may be called outside of the fragment lifecycle.

    * and thus has no ordering guarantees with regard to fragment lifecycle method calls.

    *

    * @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 rely 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 rely 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?

    Android

    作者:碎语说

    链接:http://www.jianshu.com/p/a9da7297e9d3

    來源:简书

    著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。

    相关文章

      网友评论

        本文标题:View的可见性与图片加载优化

        本文链接:https://www.haomeiwen.com/subject/pbamdxtx.html