2011-08-02 40 views
1

我想充气R.id.catText,但它并没有显示如果我膨胀它本身。如果我膨胀R.id.assets(容器),那么这两个元素显示正常。我只是不想要容器。我如何膨胀R.id.catText没有膨胀R.id.assets充气查看与充气元件

另外,我可以膨胀R.id.catText到一个对象?例如。

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

我的代码:

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); 

我的风格:

<?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> 

回答

2

LayoutInflater只适用于R.layout.*。如果你想膨胀只是TextView,你应该把它放在它自己的布局XML文件。如果您有时需要容器但不需要其他容器,则可以在容器布局中包含TextView

在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"/> 

在容器XML文件:

<?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> 

然后你就可以抬高你需要哪一个。

+0

我相信回答这个问题,就到下一个! – Jacksonkr

0

创建视图对象从XML布局并不真的需要一个充气电话。你应该使用findViewByID来初始化视图,即在这种情况下TextView。

你能解释一下你正在尝试使用TextView的充气呼叫吗?

+0

我想多次使用TextView。我只是在XML中设计它,然后想在应用程序中使用它。现在它是一个循环。 – Jacksonkr