我想以编程方式添加到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_marginLeft
and被忽略了,我看不到添加的 TextView 周围的任何边距。android:layout_marginRight
scale.xml
我在向 ExpandableListView 添加标题视图时发现了问题 Android: ClassCastException但在我的情况下,我在使用充气机的第一行有异常。