zoukankan      html  css  js  c++  java
  • Android关于inflate的root参数

    最近在用View inflate(Context context, int resource, ViewGroup root)方法时,在第三个参数root上碰到了点麻烦。

    一般在写ListView的adapter时,会这样加载自定义列

    View imageLayout = inflate(getContext(),R.layout.item_album_pager, null);
    ...
    viewGroup.addView(imageLayout);

    如果这样写,调用imageLayout时就可能出问题

    //在inflate时就把layout加入viewGroup
    View imageLayout = inflate(getContext(),R.layout.item_album_pager, viewGroup);

    这是由于,inflate方法在第三个参数root不为空时,返回的View就是root,而当root为空时,返回的才是加载的layout的根节点。看api解释:

    Inflate a new view hierarchy from the specified xml resource. Throws InflateException if there is an error.
    
    Parameters:
    resource ID for an XML layout resource to load (e.g., R.layout.main_page)
    root Optional view to be the parent of the generated hierarchy.
    Returns:
    The root View of the inflated hierarchy. If root was supplied, this is the root View; otherwise it is the root of the inflated XML file.

    本人便是在ViewPager的adapter中,使用了root不为空的inflate方法,在返回layout时出错了。

    @Override
            public Object instantiateItem(ViewGroup viewGroup, int position) {
    
                View imageLayout = inflate(getContext(),R.layout.item_album_pager, viewGroup);
                            ....
                //这里实际上把整个viewGroup返回了,导致出错
                return imageLayout;
            }

    这里举例的是View类自带的inflate方法,它本质调用的就是LayoutInflater类的 View inflate(int resource, ViewGroup root)方法。

    public static View inflate(Context context, int resource, ViewGroup root) {
            LayoutInflater factory = LayoutInflater.from(context);
            return factory.inflate(resource, root);
        }
  • 相关阅读:
    php安装yaf,memcache,memcached模块
    django的ORM操作
    Composer简介
    MySQL中exists和in的区别及使用场景
    MySQL事务原理浅析
    MySQL JOIN原理
    mysql 子句、子查询、连接查询
    多表连接的三种方式详解 HASH JOIN MERGE JOIN NESTED LOOP
    数据库多表连接方式介绍-HASH-JOIN
    MySQL中的case when 中对于NULL值判断的坑
  • 原文地址:https://www.cnblogs.com/linjzong/p/4240841.html
Copyright © 2011-2022 走看看