I am trying to add TextViews
to my xml-defined layout in code.
I have a xml-sheet, where a lot of Views
are defined. But I have to add some views in code, so a create a LinearLayout
in the 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>
And in this layout, I like to add my 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);
But I only get the following error message:
: java.lang.ClassCastException: android.widget.TextView
How can I do it?
Thanks for you help. Martin
You should use something similar to this for adding TextView to LinearLayout dynamically:
getActivity() is used for inside Fragments, you can use context or anything similar per each instance you are inside.
try using
also make sure that the layout params you're creating are LinearLayout.LayoutParams...
Hey i have checked your code, there is no serious error in your code. this is complete code:
main.xml:-
this is Stackoverflow.java
copy this code, and run it. it is completely error free. take care...
You can add a
TextView
to your linear layout programmatically like this:You need to access the layout via it's layout resource, not an id resource which is not guaranteed unique. The resource reference should look like R.layout.my_cool_layout where your above XML layout is stored in res/layout/my_cool_layout.xml.