Jacksonkr
Jacksonkr

Reputation: 32247

inflating view vs inflating an element

I would like to inflate R.id.catText, but it doesn't ever show if I inflate it by itself. If I inflate R.id.assets (the container) then both elements show up just fine. I just don't want the container. How can I inflate R.id.catText without inflating R.id.assets ?

Also, can I inflate R.id.catText to an object? eg.

TextView catText = inflater.inflate(R.id.catText);
someView.addView(new catText());

my code:

LinearLayout myRoot = (LinearLayout) findViewById(R.id.assets);
LayoutInflater inflater = (LayoutInflater)this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View view = inflater.inflate(R.layout.assets, myRoot, false);

my style:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 
 android:layout_width="match_parent" 
 android:layout_height="match_parent" 
 android:weightSum="1" 
 android:padding="50px" android:id="@+id/assets">
    <TextView android:id="@+id/catText" android:text="TextView" android:layout_width="wrap_content" android:layout_height="wrap_content" android:textColor="#ff0000"></TextView>
</LinearLayout>

Upvotes: 1

Views: 579

Answers (2)

blazeroni
blazeroni

Reputation: 8350

The LayoutInflater works on R.layout.* only. If you want to inflate just the TextView, you should put it in its own layout XML file. If you need the container sometimes but not others, you can include the TextView in the container layout.

In catText.xml:

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

In the container xml file:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 
    android:layout_width="match_parent" 
    android:layout_height="match_parent" 
    android:weightSum="1" 
    android:padding="50px"
    android:id="@+id/assets">
    <include layout="@layout/catText"/>
</LinearLayout>

Then you can inflate whichever one you need.

Upvotes: 2

Kumar Bibek
Kumar Bibek

Reputation: 9117

Creating View objects from the XML layouts doesn't really need a inflate call. You should be using findViewByID for initializing Views, ie, TextView in this case.

Could you explain for what exactly you are trying to use an inflate call for the TextView?

Upvotes: 0

Related Questions