我正在尝试在代码中向我的xml定义的布局中添加TextViews
。
我有一个xml文件,在其中定义了许多Views
。但是我需要在代码中添加一些视图,因此在xml文件中创建了一个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
我该如何做?
谢谢你的帮助。 马丁
setContentView(R.layout.your_xml_layout);
是否真正加载了正确的xml?您是否有其他使用android:id =“@+id / info”
的xml布局,这恰好是一个TextView? - Rodja