How to add a TextView to LinearLayout in Android
Asked Answered
P

9

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

Pat answered 8/7, 2010 at 14:51 Comment(4)
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.Jesselton
You are right, linearLayout is a TextView, but why? I have defined it in the xml-file as a LinearLayout ...Pat
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?Coequal
Is this issue resolved? Kindly accept as answer or post one.Humor
R
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...

Raeraeann answered 8/7, 2010 at 15:36 Comment(2)
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... ???Pat
Why would that change anything? All it does is cast sooner rather than later, which should have the same effect.Buoyage
I
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...

Innermost answered 16/9, 2011 at 13:9 Comment(3)
What if I wanted to have the following TextView: <TextView android:id="@+id/tvDInfo3" android:layout_width="0dp" android:layout_height="wrap_content" android:textStyle="bold" android:text="Release Date" android:gravity="center" android:padding="@dimen/dyk_text_pad" android:textColor="#000000" android:textSize="@dimen/info_text_size" android:layout_weight="1" />Diptych
+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.Dormer
How to do it inside button click onClick(View v)Scurlock
M
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);
Microbarograph answered 9/2, 2012 at 14:1 Comment(4)
What is MyClass.this? I'm new to Android development; am I supposed to substitute the name of my fragment class in for "MyClass"?Torrlow
MyClass.this is a context and a text view takes in a contextAngelika
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.Firedog
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)Firedog
L
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);
}
Lalittah answered 16/6, 2016 at 9:28 Comment(1)
has to define, linear.addView(childLayout);, linear as Linear Layout at firstTuranian
S
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)
Searchlight answered 22/8, 2020 at 18:13 Comment(0)
B
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.

Boxboard answered 7/3, 2018 at 11:56 Comment(0)
P
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.

Poolroom answered 9/4, 2011 at 10:56 Comment(0)
J
0
LinearLayout.LayoutParams layoutParams ;
layoutParams= new LinearLayout.LayoutParams(LinearLayout.LayoutParams.FILL_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
Jannery answered 23/8, 2013 at 22:42 Comment(0)
T
-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);
Toyatoyama answered 10/1, 2015 at 5:30 Comment(2)
Have you tested this?Unreadable
Yes, I have. And it works perfectly! Have you tried it?Toyatoyama

© 2022 - 2024 — McMap. All rights reserved.