如何通过仅膨胀一次将相同的视图添加到父级多次 [英] How to add same view to parent multiple times by inflating it only once

查看:19
本文介绍了如何通过仅膨胀一次将相同的视图添加到父级多次的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个以垂直方向作为父级的 LinearLayout,我想以编程方式多次向该父级添加一些视图.现在,在添加到父元素之前,每次获取对每个 UI 元素的新引用时,我都会膨胀子元素.这似乎不是很有效,有没有更好的方法来做到这一点.

I have a LinearLayout with vertical orientation as parent, I want to add some view programmatically multiple times to this parent. Right now I am inflating the child every time getting new references to every UI element before adding to parent. This doesn't seem to be very efficient, is there any better way of doing this.

我正在使用的当前代码如下,如果我在 for 循环之前只膨胀一次,我会收到运行时错误他指定的孩子已经有一个父级.您必须先在子级的父级上调用 removeView()."

Current code I am using is below, If I inflate only once before for loop I get runtime error "he specified child already has a parent. You must call removeView() on the child's parent first."

        LayoutInflater inflator = LayoutInflater.from(getBaseContext());
        LinearLayout parentPanel = findViewById(R.id.parent_pannel);

        ArrayList<String> myList = getData();
        for(String data : myList) {
            // inflate child
            View item = inflator.inflate(R.layout.list_item, null);
            // initialize review UI
            TextView dataText = (TextView) item.findViewById(R.id.data);
            // set data
            dataText.setText(data);
            // add child
            parentPanel.addView(item);
        }

推荐答案

你是否真的检查过 inflate 是否很慢?据我所知,膨胀视图非常快(几乎和手动创建视图一样快).

Did you actually check if inflate is slow? As far as I know, inflating view is very fast (almost as fast as creating views manually).

您可能会感到惊讶,但实际上 inflate 根本不解析 XML.用于布局的 XML 在编译时被解析和预处理 - 它们以二进制形式存储,这使得视图膨胀非常有效(这就是为什么你不能从运行时生成的 XML 膨胀视图).

It might be surprising for you to hear but inflate in fact does not parse the XMLs at all. XMLs for layout are parsed and pre-processed at compile time - they are stored in a binary form which makes view inflation very efficient (that's why you cannot inflate a view from an XML generated at runtime).

这篇关于如何通过仅膨胀一次将相同的视图添加到父级多次的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆