资料 | 汇总AndroidAndroid开发

ViewPager嵌套一个Fragment通过点击外部按钮切换不

2017-02-23  本文已影响384人  鲁克巴克诗

今天项目中有个新需求,需要在同一个fragment里面切换不同的数据,这本不是难事,但是由于fragment是嵌套在ViewPager里面的,而这个切换数据的按钮是在外部的。通过外部的按钮点击,需要控制viewPager里的Fragment变化数据,oh~It is not easy~

先看效果图:

show.gif

效果图看完,就该讲讲怎么实现的了。
  首先,我想大家都注意到了那个切换数据的小图标,对,它就是我说的外部按钮。通过点击它,下边的fragment会从服务器获取不同的数据并展示出来。似乎是蛮简单的,但因为之前项目这块是采用ViewPager+Fragment实现的,而我为了防止以后项目的修改,并不打算拆掉这对CP。那么我点击了之后,该怎么通知fragment刷新数据呢?
   说不定有小伙伴想到了,那就是adapter.notifyDataSetChanged(),然,事实上,并没有什么用。

timg.jpg

因为FragmentPagerAdapter任性啊!被折磨的懵逼的只好去找百度,看看它有没有好办法,结果还真找到了,那就是下边的代码~

@Override
    public int getItemPosition(Object object) {
        return POSITION_NONE;
    }

没错,任性的FragmentPagerAdapter有一个获取item位置状态的方法,这个方法原来不长这样的,看下边~

 /**
     * Called when the host view is attempting to determine if an item's position
     * has changed. Returns {@link #POSITION_UNCHANGED} if the position of the given
     * item has not changed or {@link #POSITION_NONE} if the item is no longer present
     * in the adapter.
     *
     * <p>The default implementation assumes that items will never
     * change position and always returns {@link #POSITION_UNCHANGED}.
     *
     * @param object Object representing an item, previously returned by a call to
     *               {@link #instantiateItem(View, int)}.
     * @return object's new position index from [0, {@link #getCount()}),
     *         {@link #POSITION_UNCHANGED} if the object's position has not changed,
     *         or {@link #POSITION_NONE} if the item is no longer present.
     */
    public int getItemPosition(Object object) {
        return POSITION_UNCHANGED;
    }

看了修改后的代码和源码,就发现POSITION_NONE(没位置)和POSITION_UNCHANGED(位置未改变)这两个值的重要性,它到底是干啥的??


先从notifyDataSetChanged()出发


 /**
     * This method should be called by the application if the data backing this adapter has changed
     * and associated views should update.
     */
    public void notifyDataSetChanged() {
        mObservable.notifyChanged();
    }

发现mObservable.notifyChanged()

 /**
     * Invokes {@link DataSetObserver#onChanged} on each observer.
     * Called when the contents of the data set have changed.  The recipient
     * will obtain the new contents the next time it queries the data set.
     */
    public void notifyChanged() {
        synchronized(mObservers) {
            // since onChanged() is implemented by the app, it could do anything, including
            // removing itself from {@link mObservers} - and that could cause problems if
            // an iterator is used on the ArrayList {@link mObservers}.
            // to avoid such problems, just march thru the list in the reverse order.
            for (int i = mObservers.size() - 1; i >= 0; i--) {
                mObservers.get(i).onChanged();
            }
        }
    }

发现mObservers.get(i).onChanged()

public abstract class DataSetObserver {
    /**
     * This method is called when the entire data set has changed,
     * most likely through a call to {@link Cursor#requery()} on a {@link Cursor}.
     */
    public void onChanged() {
        // Do nothing
    }

    /**
     * This method is called when the entire data becomes invalid,
     * most likely through a call to {@link Cursor#deactivate()} or {@link Cursor#close()} on a
     * {@link Cursor}.
     */
    public void onInvalidated() {
        // Do nothing
    }
}

是的,看到这里,发现onChanged()所在一个抽象类DataSetObserver ,似乎没有路了呢,该咋办?没关系,AS有个快捷键Alt+回车,可以看哪些源码类继承了此类!

Paste_Image.png
有没有柳暗花明又一村的感觉,我们看到了熟悉的ViewPager了,点进去看看吧~
private class PagerObserver extends DataSetObserver {
        @Override
        public void onChanged() {
            dataSetChanged();
        }
        @Override
        public void onInvalidated() {
            dataSetChanged();
        }
    }

在ViewPager类的内部类PagerObserver里又看到亲切的onChanged(),下一步走进 dataSetChanged();

 void dataSetChanged() {
        // This method only gets called if our observer is attached, so mAdapter is non-null.
        //省略前边部分……
        for (int i = 0; i < mItems.size(); i++) {
            final ItemInfo ii = mItems.get(i);
            //***********************我们要找的getItemPosition出现了!!!!***********************
            final int newPos = mAdapter.getItemPosition(ii.object);
            //***********************我们要找的getItemPosition出现了!!!!***********************

            if (newPos == PagerAdapter.POSITION_UNCHANGED) {
                continue;
            }

            if (newPos == PagerAdapter.POSITION_NONE) {
                mItems.remove(i);
                i--;

                if (!isUpdating) {
                    mAdapter.startUpdate(this);
                    isUpdating = true;
                }

                mAdapter.destroyItem(this, ii.position, ii.object);
                needPopulate = true;

                if (mCurItem == ii.position) {
                    // Keep the current item in the valid range
                    newCurrItem = Math.max(0, Math.min(mCurItem, adapterCount - 1));
                    needPopulate = true;
                }
                continue;
            }

            if (ii.position != newPos) {
                if (ii.position == mCurItem) {
                    // Our current item changed position. Follow it.
                    newCurrItem = newPos;
                }

                ii.position = newPos;
                needPopulate = true;
            }
        }
           //省略后边部分……
    }

这段代码真是长啊,不过我们可以不看其他部分,只看我们需要的部分就好,下边我再精简一下,只拿出我们需要的部分代码~

for (int i = 0; i < mItems.size(); i++) {
            final ItemInfo ii = mItems.get(i);
            final int newPos = mAdapter.getItemPosition(ii.object);
            if (newPos == PagerAdapter.POSITION_UNCHANGED) {
                continue;
            }

            if (newPos == PagerAdapter.POSITION_NONE) {
                mItems.remove(i);
                i--;
                }
}

上边的代码,看着不费劲了吧~,这是一个for循环,循环里逐一遍历item,并通过getItemPosition获取到item的位置状态,如果item的位置状态等于PagerAdapter.POSITION_UNCHANGED(位置无改变)的话,就继续。如果等于PagerAdapter.POSITION_NONE(没有位置)的话,就逐一删除对应的item。没有item了,viewPager就会重绘整个item列表了。这时,也就知道为什么,我们要重写
getItemPosition方法并返回POSITION_NONE了!恩,就是如此,我们想要的切换按钮,刷新数据就实现了哈哈哈,撒花

上一篇下一篇

猜你喜欢

热点阅读