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);
        }
  • 相关阅读:
    IQueryable & IEnumberable 区别
    修改ScriptBundle 生成顺序
    使用C#的HttpWebRequest模拟登陆网站
    XMLHttpRequest 对象
    【.Net平台下插件开发】-MEF与MAF初步调研
    MVC+UnitOfWork+Repository+EF 之我见
    关于Repository模式
    MVC中的Repository模式
    MVC Repository模式
    从Membership 到 .NET4.5 之 ASP.NET Identity
  • 原文地址:https://www.cnblogs.com/linjzong/p/4240841.html
Copyright © 2011-2022 走看看