Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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
    profileLayout.addView(temporaryProfile);

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().

like image 854
Marty Miller Avatar asked Feb 03 '12 01:02

Marty Miller


1 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.

like image 159
Brian Dupuis Avatar answered Nov 14 '22 18:11

Brian Dupuis