How to add same view to parent multiple times by inflating it only once

最后都变了- 提交于 2019-11-28 10:40:28

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).

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).

I'm not sure what your view is but have you creating it manually over inflating the XML:

   ArrayList<String> myList = getData();
    for(String data : myList) {

        LinearLayout layout = new LinearLayout(this);
        layout.setLayoutParams(new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT,             LayoutParams.WRAP_CONTENT));
        TextView textView = new TextView(this);
        textView.setLayoutParams(new LinearLayout.LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT));

        textView.setText(data);

        layout.addChild(textView);         

        parentPanel.addView(layout);
    }

But yeah your clearly attempting something that has been done for you with Simple ListView & API

You can't, even if you try to create a new view from the old view object the object will be passed by reference not value, and hence you will got an Exception as the childAlreadyHasParent, and so, the only way is to put the view into a for loop with the number of times you want it to be inflated, and this loop must contain the creating process from beginning not only the inflating lines.

Inflating multiple times cannot be done the same way doing it in single shot. Hope this works

LayoutInflater inflator = (LayoutInflater).getSystemService(Context.LAYOUT_INFLATER_SERVICE);

    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);
    }

This will work, at the least worked me

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!