How to get a view from the resource?

I have a user interface, I build it dynamically. I would like to put some component in the xml resource file. So I:

<?xml version="1.0" encoding="utf-8"?> <TextView xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+android:id/titreItem" android:layout_width="wrap_content" android:layout_height="wrap_content"> </TextView> 

... in the res/layout/titreitem.xml , as I see anywhere. But I don’t understand how to make it enable my user interface. So, inside activity.onCreate , I want to do something like:

 RelativeLayout myBigOne = new RelativeLayout(this); TextView thingFromXML = [what here ? ]; myBigOne.addView(thingFromXML); setContentView(myBigOne); 
+6
source share
2 answers

The approach seems a bit wrong. You have to put the RelativeLayout in xml, like your TextView, and inflate the whole xml. After that, you can freely add views to your layout. So do the following:

 <?xml version="1.0" encoding="utf-8"?> <RelativeLayout android:id="@+androi:id/relLayout> <TextView xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+android:id/titreItem" android:layout_width="wrap_content" android:layout_height="wrap_content"> </TextView> </RelativeLayout> 

In your activity:

 setContentView(R.layout.titreitem); RelativeLayout layout = (RelativeLayout)findViewByid(R.id.relLayout); layout.addView(...); 
+8
source

Use LayoutInflater .... The whole layout can be pumped up without creating it dynamically ....

 LayoutInflater li = LayoutInflater.from(context); View theview = li.inflate(R.layout.whatever, null); 
+28
source

All Articles