Reso Alexandro
Reso Alexandro

Reputation: 31

Add TextView to LinearLayout

I defined textview in xml and i try to add textview to linearlayout programmatically 10 times.

This is my code.

public class MainActivity extends ActionBarActivity {

    private TextView htext;
    private LinearLayout linearlayout;

    public void init()

    {
        linearlayout = (LinearLayout) findViewById(R.id.itemLayout0);
        htext = (TextView) findViewById(R.id.hText0);
    }

    private void addtext() {

        for (int i = 1; i <= 10; i++) {

            htext.setText(i + "");
            linearlayout.addView(htext);
        }

    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_main);
        init();
        addtext();
    }
}

And Xml

<LinearLayout 
android:id="@+id/itemLayout0"
android:layout_width="match_parent"
android:layout_height="89dp"
android:background="@drawable/title_background"
android:clickable="true"
android:orientation="vertical" >

<TextView
    android:id="@+id/hText0"
    android:layout_width="100sp"
    android:layout_height="100sp"
    android:layout_alignParentTop="true"
    android:layout_centerHorizontal="true"
    android:text="No data"
    android:textSize="15dp"
    android:textStyle="bold" />


     </LinearLayout>

Bu it doesnt work. I think the problem is

linearlayout.addView(htext); 

How can i fix it ?

Upvotes: 0

Views: 5397

Answers (2)

nstosic
nstosic

Reputation: 2614

The problem is that the TextView you are adding is already in the View hierarchy and has its layout parameters set, so when you call linearLayout.addView(htext); it references the same TextView that is already added in the .xml file.

You need to create a new instance of TextView and add it to the View hierarchy, using addView() method, like M D wrote.

Upvotes: 0

M D
M D

Reputation: 47817

Create TextView dynamically like

 TextView htext =new TextView(this);
 htext.setText("Test");
 htext.setId(5);
 htext.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT,LayoutParams.WRAP_CONTENT));

and then add to Layout

 linearlayout.addView(htext);

Upvotes: 6

Related Questions