145

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

Samet ÖZTOPRAK
  • 3,112
  • 3
  • 32
  • 33
Martin
  • 1,571
  • 3
  • 10
  • 5
  • Which line is that exception for? It must be from the LinearLayout cast, are you sure the linearLayout variable is a LinearLayout and not a TextView? Also you shouldn't be specifying the Id since you can't guarantee it will be unique. – Robby Pond Jul 08 '10 at 15:06
  • 1
    You are right, linearLayout is a TextView, but why? I have defined it in the xml-file as a LinearLayout ... – Martin Jul 08 '10 at 15:14
  • 1
    Make sure you are really operating on the xml shown above. Is `setContentView(R.layout.your_xml_layout);` really loading the right xml? Do you have other xml layouts where you use `android:id="@+id/info"` which happen to be a TextView? – Rodja Dec 01 '11 at 10:47
  • Is this issue resolved? Kindly accept as answer or post one. – Talha Oct 13 '16 at 06:46

9 Answers9

111

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...

Lucas
  • 3,376
  • 6
  • 31
  • 46
Ben
  • 16,124
  • 22
  • 77
  • 122
  • 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 Jul 08 '10 at 15:59
  • Why would that change anything? All it does is cast sooner rather than later, which should have the same effect. – yesennes May 19 '16 at 13:06
77

Hey i have checked your code, there is no serious error in your code. this is complete code:

main.xml:-

<?xml version="1.0" encoding="utf-8"?>
<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>

this is Stackoverflow.java

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup.LayoutParams;
import android.widget.LinearLayout;
import android.widget.TextView;

public class Stackoverflow extends Activity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        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.MATCH_PARENT,LayoutParams.WRAP_CONTENT));

        ((LinearLayout) linearLayout).addView(valueTV);
    }
}

copy this code, and run it. it is completely error free. take care...

Shashanth
  • 4,995
  • 7
  • 41
  • 51
Pushpendra Kuntal
  • 6,118
  • 20
  • 69
  • 119
  • What if I wanted to have the following TextView: `` – Si8 Oct 18 '13 at 17:41
  • 1
    +1. This answer is much better than @Ben's as it contains an example of LayoutParams and how the rest of the properties of the `TextView` is initialised. This should be marked as an answer. – Subby Jun 30 '14 at 09:31
  • How to do it inside button click `onClick(View v)` – Moeez Jul 23 '22 at 11:59
23
for(int j=0;j<30;j++) {
    LinearLayout childLayout = new LinearLayout(MainActivity.this);
    LinearLayout.LayoutParams linearParams = new LinearLayout.LayoutParams(
        LayoutParams.WRAP_CONTENT,
        LayoutParams.WRAP_CONTENT);
    childLayout.setLayoutParams(linearParams);

    TextView mType = new TextView(MainActivity.this);
    TextView mValue = new TextView(MainActivity.this);

    mType.setLayoutParams(new TableLayout.LayoutParams(
        LayoutParams.WRAP_CONTENT,
        LayoutParams.WRAP_CONTENT, 1f));
    mValue.setLayoutParams(new TableLayout.LayoutParams(
        LayoutParams.WRAP_CONTENT,
        LayoutParams.WRAP_CONTENT, 1f));

    mType.setTextSize(17);
    mType.setPadding(5, 3, 0, 3);
    mType.setTypeface(Typeface.DEFAULT_BOLD);
    mType.setGravity(Gravity.LEFT | Gravity.CENTER);

    mValue.setTextSize(16);
    mValue.setPadding(5, 3, 0, 3);
    mValue.setTypeface(null, Typeface.ITALIC);
    mValue.setGravity(Gravity.LEFT | Gravity.CENTER);

    mType.setText("111");
    mValue.setText("111");

    childLayout.addView(mValue, 0);
    childLayout.addView(mType, 0);

    linear.addView(childLayout);
}
Teng-pao Yu
  • 1,313
  • 15
  • 30
vaibhav jain
  • 361
  • 3
  • 6
23

You can add a TextView to your linear layout programmatically like this:

LinearLayout linearLayout = (LinearLayout) findViewById(R.id.mylayout);
TextView txt1 = new TextView(MyClass.this);
linearLayout.setBackgroundColor(Color.TRANSPARENT);
linearLayout.addView(txt1);
wbk727
  • 8,017
  • 12
  • 61
  • 125
Deepak
  • 1,989
  • 1
  • 18
  • 20
  • What is MyClass.this? I'm new to Android development; am I supposed to substitute the name of my fragment class in for "MyClass"? – drusepth Jul 29 '12 at 19:38
  • 1
    MyClass.this is a context and a text view takes in a context – Mihai Bratulescu Aug 27 '13 at 07:03
  • 2
    Just for clarification: `MyClass.this`, in most cases, is the same as `this`. You need to specify, however, the name of the class, if you are in a nested class and want to access the instance of the "outer" class, which is very common when defining callbacks for the events in android. – drigoangelo Nov 19 '14 at 11:56
  • I guess some android developers got used to putting the name of the class where it's needed and started putting it everywhere. Also, `MyClass.this` is an instance of `MyClass`, and it will only be a context if MyClass implements Context (e.g. extends Activity) – drigoangelo Nov 19 '14 at 12:01
12

In Kotlin you can add Textview as follows.

 val textView = TextView(activity).apply {
            layoutParams = LinearLayout.LayoutParams(
                LinearLayout.LayoutParams.MATCH_PARENT,
                LinearLayout.LayoutParams.WRAP_CONTENT
            ).apply {
                setMargins(0, 20, 0, 0)
                setPadding(10, 10, 0, 10)
            }
            text = "SOME TEXT"
            setBackgroundColor(ContextCompat.getColor(this@MainActivity, R.color.colorPrimary))
            setTextColor(ContextCompat.getColor(this@MainActivity, R.color.colorPrimaryDark))
            textSize = 16.0f
            typeface = Typeface.defaultFromStyle(Typeface.BOLD)
        }
 linearLayoutContainer.addView(textView)
Salman Nazir
  • 2,759
  • 2
  • 28
  • 42
11

You should use something similar to this for adding TextView to LinearLayout dynamically:

LinearLayout linearLayout = getActivity().findViewById(R.id.infoLayout);

TextView valueTV = new TextView(context);
valueTV.setText("hallo hallo");
valueTV.setId(Integer.parseInt("5"));
valueTV.setLayoutParams(new LinearLayout.LayoutParams(
       LinearLayout.LayoutParams.FILL_PARENT,
       LinearLayout.LayoutParams.WRAP_CONTENT));

linearLayout.addView(valueTV);

getActivity() is used for inside Fragments, you can use context or anything similar per each instance you are inside.

Noir
  • 198
  • 1
  • 7
3

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.

penguin359
  • 1,289
  • 13
  • 26
0
LinearLayout.LayoutParams layoutParams ;
layoutParams= new LinearLayout.LayoutParams(LinearLayout.LayoutParams.FILL_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
Zapnologica
  • 22,170
  • 44
  • 158
  • 253
-1

Here's where the exception occurs

((LinearLayout) linearLayout).addView(valueTV);

addView method takes in a parameter of type View, not TextView. Therefore, typecast the valueTv object into a View object, explicitly.

Therefore, the corrected code would be :

((LinearLayout) linearLayout).addView((TextView)valueTV);
sfmirtalebi
  • 370
  • 7
  • 16
user3509153
  • 343
  • 2
  • 7