我试图TextViews在代码中添加到我的xml定义的布局.我有一个xml表,其中Views定义了很多.但是我必须在代码中添加一些视图,所以LinearLayout在xml-sheet中创建一个:
<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>
Run Code Online (Sandbox Code Playgroud)
在这个布局中,我想添加我的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);
Run Code Online (Sandbox Code Playgroud)
但我只收到以下错误消息:
: java.lang.ClassCastException: android.widget.TextView
Run Code Online (Sandbox Code Playgroud)
我该怎么做?
谢谢你的帮助.马丁
我试图以编程方式将视图添加到线性布局.
LinearLayout layout = (LinearLayout) findViewById(R.id.info);
String [] informations = topOffer.getInformations();
TextView informationView;
View line = new View(this);
line.setLayoutParams(new LayoutParams(1, LayoutParams.FILL_PARENT));
line.setBackgroundColor(R.color.solid_history_grey);
for (int i = 0; i < informations.length; i++) {
informationView = new TextView(this);
informationView.setText(informations[i]);
layout.addView(informationView, 0);
layout.addView(line, 1);
}
Run Code Online (Sandbox Code Playgroud)
首先,我只添加了informationsView,一切正常.在添加了line-View之后,它崩溃了,出现以下错误:
java.lang.IllegalStateException:指定的子级已有父级.您必须首先在孩子的父母上调用removeView().
所以我尝试了addView(View v,int index),但它崩溃了同样的消息......
有人有解决方案吗?
谢谢,马丁