37

I was trying the following code and was getting an error because there is no such constructor defined.

View v = new View(findViewById(R.id.divider));

Is there any simple way to copy a view into another?

Mani Sankar
  • 800
  • 1
  • 9
  • 19
  • Hope this will solve your problem http://stackoverflow.com/questions/4159211/how-do-i-clone-a-view http://stackoverflow.com/questions/14798826/duplicate-views-on-android-during-run-time – Adeel Jun 24 '16 at 11:34
  • Possible duplicate of [How to create Clone-Duplicate View?](http://stackoverflow.com/questions/29744039/how-to-create-clone-duplicate-view) – Shaishav Jogani Aug 25 '16 at 05:09

1 Answers1

49

Apparently you cannot clone views as stated by these answers:

How do I clone a View?

How to create Clone-Duplicate View?

If you inflated the first view from XML the way to go seems to be inflating the second view from XML, too.

To inflate your view from XML put it into an extra layout file, e.g. "textview.xml"

<?xml version="1.0" encoding="utf-8"?>
<TextView
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Hello World!" />

Then, inflate it from XML in your onCreate():

View view = LayoutInflater.from(this).inflate(R.layout.textview, null);
myLayout.addView(view);
Community
  • 1
  • 1
Tobias Uhmann
  • 2,757
  • 2
  • 25
  • 35
  • 1
    What if we require it in a function that outside onCreate() ? any idea ? – Hissaan Ali Aug 25 '19 at 14:23
  • 1
    @SyedHissaan Create a global variable to hold your context: `Context contextApp;`. Then in OnCreate, populate the variable: `contextApp = this`. In a function outside of OnCreate, where you would normally put, "this", instead put, "contextApp". – Adam Komar Sep 06 '19 at 17:37
  • what about canvas libs, where xml doesn't exist? – Georgiy Chebotarev Oct 09 '19 at 12:10