Inflate layout programmatically within another layout

前端 未结 8 2065
心在旅途
心在旅途 2020-11-30 04:54

I need help with my android app. I need inflate a layout within another layout and I dont know how I do. My xml code is this:

  • item.xml - I need inflate mult

8条回答
  •  误落风尘
    2020-11-30 04:59

    Below is a working code from one of my projects:

    // The parent container
    mNotificationOverlay = (LinearLayout) findViewById(R.id.container_destacado);   
    LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    
    for (Message message : m) {
    
        // Inflate the child layout on the fly
        final View notificationContainer = inflater.inflate(R.layout.notification_overlay_linear_layout, null);
        notificationContainer.setTag(message.getNotificationId());
    
        // Access children of child container
        TextView notificationOverlayTitle = (TextView) notificationContainer.findViewById(R.id.notification_title_overlay);
        TextView notificationOverlayBody = (TextView) notificationContainer.findViewById(R.id.notification_body_overlay);
        ImageButton notificationOverlayCancelButton = (ImageButton) notificationContainer.findViewById(R.id.notification_cancel_overlay);
    
        // Perform desired operations
        notificationOverlayCancelButton.setTag(message.getNotificationId());
        notificationOverlayTitle.setText(message.getTitle());
        notificationOverlayBody.setText(message.getNotificationBody());
        mNotificationOverlay.setVisibility(View.VISIBLE);
    
        // Attach any listeners
        attachListenersToCancelView(notificationOverlayCancelButton);
    
        // Add view to parent container
        mNotificationOverlay.addView(notificationContainer);
    }
    

    Hope that helps!

提交回复
热议问题