1

我想以编程方式添加到LinearLayout一些TextViews. 我想使用LayoutInflater. 我在我的活动布局 xml 文件中有:

<LinearLayout
     android:id="@+id/linear_layout"
     android:layout_width="wrap_content"
     android:layout_height="fill_parent"
     android:orientation="vertical"
     />

我在下面这样写了活动代码。

LinearLayout linearLayout = (LinearLayout) findViewById(R.id.linear_layout);
LayoutInflater inflater = (LayoutInflater) getApplicationContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE); 
TextView textView = (TextView) inflater.inflate(R.layout.scale, linearLayout, true);
textView.setText("Some text");
linearLayout.addView(textView);

我的scale.xml文件看起来像:

<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
     android:layout_width="wrap_content"
     android:layout_height="wrap_content"
     android:layout_weight="1"
     android:layout_marginLeft="50dp"
     android:layout_marginRight="50dp"  
     android:drawableTop="@drawable/unit"
     />

在这条线上TextView textView = (TextView) inflater.inflate(R.layout.scale, linearLayout, true);,我有下面这样的致命异常。

 java.lang.RuntimeException: Unable to start activity ComponentInfo{my.package/my.package.MyActivity}: 
 java.lang.ClassCastException: android.widget.LinearLayout
 Caused by: java.lang.ClassCastException: android.widget.LinearLayout

当我用 null 替换有问题的行时linearLayout,我没有任何异常,但是我的android:layout_marginLeftand被忽略了,我看不到添加的 TextView 周围的任何边距。android:layout_marginRightscale.xml

在向 ExpandableListView 添加标题视图时发现了问题 Android: ClassCastException但在我的情况下,我在使用充气机的第一行有异常。

4

1 回答 1

3

linearLayout当您在对 的调用中指定根视图 ( ) 时inflater.inflate(),膨胀的视图会自动添加到视图层次结构中。因此,您无需调用addView. 此外,正如您所注意到的,返回的视图是层次结构的根视图 (a LinearLayout)。要获取对TextView自身的引用,您可以使用以下方法检索它:

LinearLayout linearLayout = (LinearLayout) findViewById(R.id.linear_layout);
LayoutInflater inflater = (LayoutInflater) getApplicationContext().
    getSystemService(Context.LAYOUT_INFLATER_SERVICE); 
inflater.inflate(R.layout.scale, linearLayout, true);
TextView textView = (TextView) linearLayout.getChildAt(
    linearLayout.getChildCount()-1);
textView.setText("Some text");

如果要android:id在 scale.xml 中为视图提供一个属性,则可以使用

TextView textView = (TextView) linearLayout.findViewById(R.id.text_id);
于 2012-03-11T21:17:38.483 回答