如何在listview中已经膨胀的视图中动态添加视图?

时间:2016-02-12 06:11:30

标签: android listview layout-inflater

通过这样做可以动态添加视图:

getView():

 @Override
    public View getView(int position, View convertView, ViewGroup parent) {

        HeaderViewHolder viewHolder = null;
        Map.Entry<String, List<FindTopicFragment.MaintainTopicModel>> hashMap = getItem(position);

        if (null == convertView) {
            convertView = inflater.inflate(R.layout.post_group_list_header, null);
            viewHolder = new HeaderViewHolder();
            viewHolder.header_text = (TextView) convertView.findViewById(R.id.header_text);
            viewHolder.linearLayout = (LinearLayout) convertView.findViewById(R.id.linearItems);
            convertView.setTag(viewHolder);
            setItems(hashMap.getValue().get(position).topicModels, position, viewHolder);
        } else {
            viewHolder = (HeaderViewHolder) convertView.getTag();
        }

        viewHolder.header_text.setText("" + hashMap.getKey());

        return convertView;
    }

在列表视图中已经膨胀的视图中添加视图:

private void setItems(List<FindTopicFragment.MaintainTopicModel> modelList, int position, HeaderViewHolder holder) {
        holder.linearLayout.removeAllViews();
        System.out.println("===============================");

        LayoutInflater inflater = (LayoutInflater) this.context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        View view = inflater.inflate(R.layout.post_group_list_row, null);
        TextView group_list_header = (TextView) view.findViewById(R.id.group_list_header);

        for (FindTopicFragment.MaintainTopicModel model : modelList) {
            System.out.println(model.topicKey);
            group_list_header.setText("" + model.topicKey);
            holder.linearLayout.addView(group_list_header);
        }
        System.out.println("===============================");
    }

我已经解决了这个问题。在for循环内膨胀一个视图,每次都会创建一个新行。

    private void setItems(List<FindTopicFragment.MaintainTopicModel> modelList, int position, HeaderViewHolder holder) {
            holder.linearLayout.removeAllViews();
            System.out.println("===============================");

            LayoutInflater inflater = (LayoutInflater) this.context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);

            for (FindTopicFragment.MaintainTopicModel model : modelList) {
                System.out.println(model.topicKey);
View view = inflater.inflate(R.layout.post_group_list_row, null);
            TextView group_list_header = (TextView) view.findViewById(R.id.group_list_header);
                group_list_header.setText("" + model.topicKey);
                holder.linearLayout.addView(group_list_header);
            }
            System.out.println("===============================");
        }

谢谢你们提出宝贵的建议。

1 个答案:

答案 0 :(得分:0)

group_list_header 已有父母,即视图。因此,将此添加到另一个视图组, holder.linearLayout 正在给出错误。我相信正确的行应该是

holder.linearLayout.addView(视图);