Duplicate a view programmatically from an already existing view

Mani Sankar picture Mani Sankar · Jun 24, 2016 · Viewed 24.6k times · Source

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?

Answer

Tobias Uhmann picture Tobias Uhmann · Jun 24, 2016

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);