[java] How to add a TextView to LinearLayout in Android

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

This question is related to java android xml textview android-linearlayout

The answer is


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);

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.


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)

LinearLayout.LayoutParams layoutParams ;
layoutParams= new LinearLayout.LayoutParams(LinearLayout.LayoutParams.FILL_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);

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


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.


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);
}

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


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);

Examples related to java

Under what circumstances can I call findViewById with an Options Menu / Action Bar item? How much should a function trust another function How to implement a simple scenario the OO way Two constructors How do I get some variable from another class in Java? this in equals method How to split a string in two and store it in a field How to do perspective fixing? String index out of range: 4 My eclipse won't open, i download the bundle pack it keeps saying error log

Examples related to android

Under what circumstances can I call findViewById with an Options Menu / Action Bar item? How to implement a simple scenario the OO way My eclipse won't open, i download the bundle pack it keeps saying error log getting " (1) no such column: _id10 " error java doesn't run if structure inside of onclick listener Cannot retrieve string(s) from preferences (settings) strange error in my Animation Drawable how to put image in a bundle and pass it to another activity FragmentActivity to Fragment A failure occurred while executing com.android.build.gradle.internal.tasks

Examples related to xml

strange error in my Animation Drawable How do I POST XML data to a webservice with Postman? PHP XML Extension: Not installed How to add a Hint in spinner in XML Generating Request/Response XML from a WSDL Manifest Merger failed with multiple errors in Android Studio How to set menu to Toolbar in Android How to add colored border on cardview? Android: ScrollView vs NestedScrollView WARNING: Exception encountered during context initialization - cancelling refresh attempt

Examples related to textview

Kotlin: How to get and set a text to TextView in Android using Kotlin? How to set a ripple effect on textview or imageview on Android? The specified child already has a parent. You must call removeView() on the child's parent first (Android) Android: Creating a Circular TextView? android on Text Change Listener Android - Set text to TextView Placing a textview on top of imageview in android Rounded corner for textview in android Different font size of strings in the same TextView Auto-fit TextView for Android

Examples related to android-linearlayout

Android LinearLayout : Add border with shadow around a LinearLayout How to add a fragment to a programmatically generated layout? How to center the content inside a linear layout? How to add (vertical) divider to a horizontal LinearLayout? Fit Image in ImageButton in Android How can I create a border around an Android LinearLayout? Put buttons at bottom of screen with LinearLayout? How to show shadow around the linearlayout in Android? How to add border around linear layout except at the bottom? How do I use a compound drawable instead of a LinearLayout that contains an ImageView and a TextView