Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Duplicate a view programmatically from an already existing view

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?

like image 253
Mani Sankar Avatar asked Jun 24 '16 11:06

Mani Sankar


1 Answers

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); 
like image 170
Tobias Uhmann Avatar answered Sep 22 '22 08:09

Tobias Uhmann