【发布时间】:2011-03-13 09:39:13
【问题描述】:
我正在尝试将TextViews 添加到我在代码中定义的xml 布局中。
我有一个 xml 表,其中定义了很多 Views。但是我必须在代码中添加一些视图,所以在 xml-sheet 中创建一个LinearLayout:
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:id="@+id/info"
android:layout_height="wrap_content"
android:orientation="vertical">
</LinearLayout>
在这个布局中,我喜欢添加我的TextView:
View linearLayout = findViewById(R.id.info);
//LinearLayout layout = (LinearLayout) findViewById(R.id.info);
TextView valueTV = new TextView(this);
valueTV.setText("hallo hallo");
valueTV.setId(5);
valueTV.setLayoutParams(new LayoutParams(
LayoutParams.FILL_PARENT,
LayoutParams.WRAP_CONTENT));
((LinearLayout) linearLayout).addView(valueTV);
但我只收到以下错误消息:
: java.lang.ClassCastException: android.widget.TextView
我该怎么做?
感谢您的帮助。 马丁
【问题讨论】:
-
该例外适用于哪一行?它必须来自 LinearLayout 演员,您确定 linearLayout 变量是 LinearLayout 而不是 TextView?此外,您不应该指定 ID,因为您不能保证它是唯一的。
-
你是对的,linearLayout是一个TextView,但是为什么呢?我已在 xml 文件中将其定义为 LinearLayout ...
-
确保你真的在上面显示的xml上操作。
setContentView(R.layout.your_xml_layout);真的在加载正确的 xml 吗?您是否还有其他使用android:id="@+id/info"的 xml 布局,恰好是 TextView? -
这个问题解决了吗?请接受作为答案或发布一个。
标签: java android xml textview android-linearlayout