N
N
newdancer2017-07-03 10:43:13
Android
newdancer, 2017-07-03 10:43:13

How to implement viewholder when dynamically filling linearlayout view with elements?

How to implement viewholder when dynamically filling linearlayout view with elements?
Tried like this:

private static class ProgramHolder{
        TextView textName, textSecondName, textSpecName;
    }

and see filling
for (int d = 0; d < doctors.size(); d++) {
                if (pHolder == null) {
                    pHolder = new ProgramHolder();
                    layerDoctors = mLayoutInflater.inflate(R.layout.item_doctor, null);
                    pHolder.textName = (TextView) layerDoctors.findViewById(R.id.textName);
                    pHolder.textSecondName = (TextView) layerDoctors.findViewById(R.id.textSecondName);
                    pHolder.textSpecName = (TextView) layerDoctors.findViewById(R.id.textSpecName);
                    layerDoctors.setTag(pHolder);
                }
                Doctor doctor = doctors.get(d);
                pHolder.textName.setText(doctor.getSecond_name());
                pHolder.textSecondName.setText(doctor.getFirst_name() + " " + doctor.getMiddle_name());
                pHolder.textSpecName.setText(doctor.getSpec_name());
                linDoctors.addView(layerDoctors);
            }

But I am getting an error
The specified child already has a parent. You must call removeView() on the child's parent first.

How to deal with this or how will it be right? It is necessary to add a view of about 200 elements to the linearlayout. Therefore, I wanted to make it easier to fill in order not to create a view array of 200 elements

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
Denis Zagaevsky, 2017-07-03
@zagayevskiy

o_O And what did you want to achieve in this way? You create layerDoctors once, and try to add it to the container several times. Already on the second time you get this error, because the view has already been added.
Farther. 200 elements in LinearLayout, and, apparently, not simple ones - this is a guaranteed way to get brakes. Of course, you need to use a virtualized list. For example, ListView, and, of course, with the viewholder pattern, which you almost mastered.
But I would recommend using RecyclerView right away, it is more modern and it is more difficult to make a mistake there. And in general there are a lot of goodies.
PS I'll expand the answer a bit. ViewHolder is a pattern to improve view reuse in virtualized containers.
What does virtualized mean - this means that you put more elements in the container than there are views. Views are reused as needed (out of screen boundaries).
There is no reuse in LinearLayout. You put 200 elements into it - there will be a very large memory overhead and drawing will be stupid. ViewHolder will not help here by definition.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question