What's the quickest way to add several views to a LinearLayout?

后端 未结 3 1110
醉酒成梦
醉酒成梦 2021-02-02 14:56

I have a LinearLayout view that already contains several elements. I want to add a lot more Views to it, programmatically. And because this is inside a Scroll

3条回答
  •  面向向阳花
    2021-02-02 15:14

    A ListView is the way to go.

    You say that your layout is too complex. But it is completely okay to inflate a complex layout as a child. For example a layout that has text and then an icon:

    
    
        
        
    
    

    Could be inflated in your adapter as so:

    @Override
    public View getView(final int position, View convertView, ViewGroup parent) {
        LinearLayout root = null;
        ImageView editImageView;
    
        if (convertView == null) {
            LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            root = (LinearLayout)inflater.inflate(R.layout.item, null);
        } else {
            root = (LinearLayout)convertView;
        }
    }
    

    You can also be a little more clever in order to support a header. Just add a check if the index is the root and inflate a different view. Since the header is the only one that is different you will still take advantage of all the other rows being reusable. You can even pre-inflate and store the header and reuse it to completely get rid of inflation.

提交回复
热议问题