views:

89

answers:

2

Hi,

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

A: 

try using

LinearLayout linearLayout = (LinearLayout)findViewById(R.id.info)

...

linearLayout.addView(valueTV);

also make sure that the layout params you're creating are LinearLayout.LayoutParams...

Ben
there is again an exception, because findViewById returns an TextView. But why? I fetch it with the LinearLayout id....what do you mean with:also make sure that the layout params you're creating are LinearLayout.LayoutParams... ???
Martin
A: 

I have it, it was a stupid id change mistake ... :(

Thanks for you help

Martin