73

My question is almost exactly this question:

Clone textview to append it to a ViewGroup

However, I was inflating a view, and then attempting to clone it at the object level for performance reasons (I don't want to parse XML every single time), so that answer doesn't help me. View.clone() is protected and it apparently doesn't have a copy constructor. Is there any way to do this?

Community
  • 1
  • 1
SapphireSun
  • 9,170
  • 11
  • 46
  • 59
  • 2
    Are you sure that it would be significantly faster to clone it at the object level than to inflate it twice? What is guiding that assertion? – Cheryl Simon Nov 11 '10 at 21:04
  • 1
    I suppose I phrased that wrong, it's more like I wanted to see if it would be faster. – SapphireSun Nov 11 '10 at 21:22
  • 1
    If you are creating a lot of instances of a particular view, you should probably be using a ListView or some other element that will recycle view instances as you scroll. – Cheryl Simon Nov 11 '10 at 21:48
  • 1
    The problem is that I'm doing a more complicated layout inside of a scrollview. This problem was a result of abandoning that approach. For some reason, ListViews do not behave well with ScrollViews. – SapphireSun Nov 11 '10 at 23:02
  • This thread is similar http://stackoverflow.com/questions/3900044/clone-textview-to-append-it-to-a-viewgroup – Khaled Annajar Jan 16 '13 at 14:11

1 Answers1

111

You cannot clone views, the way to do it is to inflate your View every time. Note that the XML is compiled into binary which can be parsed very efficiently.

Romain Guy
  • 97,993
  • 18
  • 219
  • 200
  • 10
    I read somewhere today that inflating views is very expensive. Especially in lists. – frostymarvelous Jun 01 '14 at 12:20
  • 6
    @frostymarvelous, It's a lot more expensive (speed-wise) than re-using already created views (though that's not always an option), but there's only a very slight difference between inflating and programmatic creation of new Views. – Reed Jun 22 '14 at 00:36
  • 6
    u cant clone a specific view! =o amazing! – M. Usman Khan Feb 24 '15 at 12:31
  • u can, just convert to bitmap as snapshot then add into imageview, but it's only image – famfamfam Mar 15 '21 at 17:33