Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create views programmatically using XML on Android

Tags:

android

xml

I want to create a UI layout in XML and have it inserted as a child into an existing view (It will be inserted multiple times).

For example, here is what the XML file will contain:

<RelativeLayout     android:id="@+id/relativeLayout1" >     <Button android:id="@+id/myButton"         android:text="@string/mystring" /> </RelativeLayout> 

Now I get the parent LinearLayout and now want to add that XML file as a child view, e.g:

LinearLayout linear = (LinearLayout) findViewById(R.id.myLayout);  // need to create a view object from the xml file linear.addView(myXmlObject); 

Is it possible to convert an XML resource to a view type? If so, how would I do this?

like image 240
Stuyvenstein Avatar asked Dec 15 '12 04:12

Stuyvenstein


People also ask

How do you add a view in XML?

Android View Class Constructors To create a new View instance from Kotlin code, it needs the Activity context. To create a new View instance from XML. To create a new view instance from XML with a style from theme attribute. To create a new view instance from XML with a style from theme attribute and/or style resource.

How do you create a programmatically view?

If you create a View via a constructor (e.g., Button myButton = new Button(); ), you'll need to call setLayoutParams on the newly constructed view, passing in an instance of the parent view's LayoutParams inner class, before you add your newly constructed child to the parent view.

What is view in Android XML?

A View occupies a rectangular area on the screen and is responsible for drawing and event handling. Views are used for Drawing Shapes like Circles,Rectangles,Ovals etc . Just Use View with background and apply a Shape using Custom Drawable.


1 Answers

I believe you want the LayoutInflater. Let's say your example XML is in a file custom_layout.xml:

LayoutInflater inflater = LayoutInflater.from(context); RelativeLayout layout = (RelativeLayout) inflater.inflate(R.layout.custom_layout, null, false);  LinearLayout linear = (LinearLayout)findViewById(R.id.myLayout); linear.addView(layout); 
like image 89
Sam Avatar answered Sep 23 '22 02:09

Sam