将TextView添加到LinearLayout时的ClassCastException
-
11-12-2019 - |
题
我想以编程方式添加到 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
当我在有问题的行替换 linearLayout
与null我没有任何例外,但 android:layout_marginLeft
和 android:layout_marginRight
从我的 scale.xml
被忽略,我看不到添加的TextView周围的任何边距。
我发现了一个问题 机器人:向ExpandableListView添加头视图时的ClassCastException 但在我的情况下,我在使用充气机的第一行有例外。
解决方案
当您指定根视图(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
按比例属性。xml,你可以用
TextView textView = (TextView) linearLayout.findViewById(R.id.text_id);
不隶属于 StackOverflow