Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get a view from a resource?

Tags:

android

I have a UI, I build it dynamically. I should want to put some component in a xml resource file. So I do :

<?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 a file res/layout/titreitem.xml as I see anywhere. But I don't understand how get it to put inside my UI. So, inside activity.onCreate, I want to do something like :

RelativeLayout myBigOne = new RelativeLayout(this);
TextView thingFromXML = [what here ? ];
myBigOne.addView(thingFromXML);
setContentView(myBigOne);
like image 369
Istao Avatar asked Dec 05 '10 09:12

Istao


2 Answers

Use a LayoutInflater....The Entire Layout can be inflated, without dynamically creating it....

LayoutInflater li = LayoutInflater.from(context);
View theview = li.inflate(R.layout.whatever, null);
like image 172
st0le Avatar answered Nov 12 '22 16:11

st0le


Approach seems to be little incorrect. You should put RelativeLayout to the xml as your TextView made, and inflate the whole xml. Afterwards, you will be free to add views to your layout. So, do this:

<?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(...);
like image 7
Vladimir Ivanov Avatar answered Nov 12 '22 17:11

Vladimir Ivanov