开发者

inflating view vs inflating an element

开发者 https://www.devze.com 2023-03-24 12:07 出处:网络
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 contain

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"></TextV开发者_开发技巧iew>
</LinearLayout>


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.


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?

0

精彩评论

暂无评论...
验证码 换一张
取 消