膨胀视图与膨胀元素

时间:2011-08-02 18:03:41

标签: java android android-inflate

我想充气 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 个答案:

答案 0 :(得分: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>

然后你可以膨胀你需要的任何一个。

答案 1 :(得分:0)

从XML布局创建View对象并不需要进行膨胀调用。你应该使用findViewByID初始化视图,在这种情况下是TextView。

你能解释一下你究竟尝试使用TextView的膨胀调用吗?

相关问题