Home » Android » Android: Is it possible to make a copy of a View?

Android: Is it possible to make a copy of a View?

Posted by: admin June 15, 2020 Leave a comment


The app I am working on requires a dynamic layout that displays a HorizontalScrollView of profiles. A profile is simply a RelativeLayout with a picture and some text. Since I get the data from a data file, I need to create a Relative layout for each of profiles. At first I created each RelativeLayout programmatically in a for loop and then added it to the parent view. This works, but I don’t want to do it this way. I want to use different layout files based on the screen size of the device, etc.

Then I thought. Well, what if I had a Layout with just one profile on it? My code could get that one profile with findViewById() and then create new ones based off of it! In other words:

    // get the layout
    profileLayout = (LinearLayout) findViewById(R.id.profileLayout);        

    // get the first profile in the layout
    originalProfile = (RelativeLayout) findViewById(R.id.profile1);

    // make copy of profile
    temporaryProfile = originalProfile;

    // make changes to the this profile and add it back

Of course, this doesn’t work because this is java and temporaryProfile is now a reference to originalProfile. So is there any way to make a copy of this RelativeLayout? I’m aware of LayoutInflater, but I still don’t understand how it works. There is also Object.clone().

How to&Answers:

Not so much. Sounds like your particular case could benefit from a ListView of some kind and an adapter (see resources like this for info). If not, then a LayoutInflater is the best answer as it does precisely what you want. Acquiring one you can then use it to “inflate” any view you’ve defined in your XML layout files and do whatever you want with it.

Here’s a great discussion of the inflater.


you can make a copy of your inflator with a new context. Layout Inflater – Android Developers


Why not simply use an include in the xml file for the layout that you want.