How to add a TextView to LinearLayout in Android How to add a TextView to LinearLayout in Android xml xml

How to add a TextView to LinearLayout in Android


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


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"?><LinearLayoutxmlns: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...


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