How to add a TextView to LinearLayout in Android

JavaAndroidXmlTextviewAndroid Linearlayout

Java Problem Overview


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

Java Solutions


Solution 1 - Java

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

Solution 2 - Java

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

Solution 3 - Java

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

Solution 4 - Java

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

Solution 5 - Java

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.

Solution 6 - Java

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)

Solution 7 - Java

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.

Solution 8 - Java

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

Solution 9 - Java

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionMartinView Question on Stackoverflow
Solution 1 - JavaBenView Answer on Stackoverflow
Solution 2 - JavaPushpendra KuntalView Answer on Stackoverflow
Solution 3 - Javavaibhav jainView Answer on Stackoverflow
Solution 4 - JavaDeepakView Answer on Stackoverflow
Solution 5 - JavaNoirView Answer on Stackoverflow
Solution 6 - JavaSalman NazirView Answer on Stackoverflow
Solution 7 - Javapenguin359View Answer on Stackoverflow
Solution 8 - JavaZapnologicaView Answer on Stackoverflow
Solution 9 - Javauser3509153View Answer on Stackoverflow