将翻页效果做成一个View之在android中的View中实现装饰模式。

来源:互联网 发布:服务器需要开放的端口 编辑:程序博客网 时间:2024/06/03 14:45

我想要让一个View 作为包装,但是其实体是一另外一个concrete View。让外界对装饰View的调用都换成对concreteView的调用。这样,就能够实现一个包装了。但是会遇到一个问题。就是很多函数是final的,比如findViewById(int id)。看下面的源码。

先把源码中的这两个函数的内容贴出来。

View.java中函数

  /**     * Look for a child view with the given id.  If this view has the given     * id, return this view.     *     * @param id The id to search for.     * @return The view that has the given id in the hierarchy or null     */    public final View findViewById(int id) {        if (id < 0) {            return null;        }        return findViewTraversal(id);    }

/**     * {@hide}     * @param id the id of the view to be found     * @return the view of the specified id, null if cannot be found     */    protected View findViewTraversal(int id) {        if (id == mID) {            return this;        }        return null;    }

ViewGroup.java中的源码:

/**     * {@hide}     */    @Override    protected View findViewTraversal(int id) {        if (id == mID) {            return this;        }        final View[] where = mChildren;        final int len = mChildrenCount;        for (int i = 0; i < len; i++) {            View v = where[i];            if ((v.mPrivateFlags & IS_ROOT_NAMESPACE) == 0) {                v = v.findViewById(id);                if (v != null) {                    return v;                }            }        }        return null;    }

注意,我们即使继承了ViewGroup 也是不能够调用findViewTraversal的。因为它是hide 函数。

而findViewById 函数是final 函数。我们不能够重载。但是我们可以从在findViewTraversal 函数,虽然该函数是hide的,但是能够重载它。其实很多时候,如果想调用hide 的函数,重载一下这个函数也是一个不错的办法。

看了源码,怎么重载该函数基本是没啥问题了。

    protected View findViewTraversal(int id) {    Log.i(TAG,"my findViewTraversal");    if (id == getId()) {            return this;        }    return concrete.findViewById(id);    }

这样,在系统调用该函数的时候,就是调用这个重载的函数了。

另外提一句,系统在解析xml布局的时候,会不断地调用该函数,获得View。

额,此文未编辑完。未完待续...

原创粉丝点击