【发布时间】:2012-03-11 21:09:09
【问题描述】:
我想以编程方式向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 时,我没有任何异常,但是我的scale.xml 中的android:layout_marginLeft 和android:layout_marginRight 被忽略了,我看不到添加的TextView 周围的任何边距。
我发现了问题Android: ClassCastException when adding a header view to ExpandableListView,但就我而言,我在使用充气机的第一行有异常。
【问题讨论】:
标签: android textview android-linearlayout layout-inflater