添加TextView到LinearLayout时的ClassCastException

问题描述:

我想以编程方式添加到LinearLayout某些TextViews。我想用LayoutInflater。我在我的活动布局的xml文件:添加TextView到LinearLayout时的ClassCastException

<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 

当我有问题的行linearLayout与空代替我没有任何异常,但是从我的scale.xmlandroid:layout_marginLeftandroid:layout_marginRight被忽略,我看不到任何利润增加周围TextView的。

我发现问题Android: ClassCastException when adding a header view to ExpandableListView但在我的情况下,我在使用充气器的第一行中有例外。

当您在调用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); 
+0

谢谢检索你,但我不明白。我的'LinearLayout'在布局文件中没有任何子视图。如何在这种情况下使用'getChildAt'方法?当我尝试使用带有LinearLayout的'inflater.inflate()'作为我的'ViewGroup'时,我有个例外。当我使用'null'作为'ViewGroup'时,我的应用程序可以工作,但在这种情况下,我再次无法使用'getChildAt'方法。 – woyaru 2012-03-11 21:26:22

+1

@woyaru - 在'inflater.inflate'返回之后,膨胀的'TextView'将被添加到'linearLayout'中。异常即将到来是因为当它实际上返回'linearLayout'本身时,您试图将返回值转换为'TextView'。 ('inflater.inflate'只有在根视图为'null'的情况下才返回虚拟视图,如果不是'null',则返回根视图,而不是虚拟视图。) – 2012-03-11 21:31:11

+0

非常感谢! – woyaru 2012-03-11 21:34:02