将TextView添加到LinearLayout时出现ClassCastException



我想以编程方式向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时,我没有任何异常,但我的scale.xml中的android:layout_marginLeftandroid:layout_marginRight被忽略了,我看不到添加的TextView周围有任何边距。

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

在对inflater.inflate()的调用中指定根视图(linearLayout)时,展开的视图会自动添加到视图层次结构中。因此,您不需要调用addView。此外,正如您所注意到的,返回的视图是层次结构的根视图(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");

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

TextView textView = (TextView) linearLayout.findViewById(R.id.text_id);

最新更新