Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamically add textViews to a linearLayout

I read this somewhere here and I totally lost it, but could use some assistance.

My app is pulling the column names from sqlite into an array. I want to create a textview and edit text for each one (via the size of the array), and I remember reading somewhere that you can treat the textViews variable names like an array, but I don't know where that is now.

So how would I dynamically create a textView and editText for however many listings are in an array?

It was something like

TextView tv[] = new TextView()...  for(...){ tv[i]... } 

Is this right?

I appreciate your help!

like image 820
Anthony Honciano Avatar asked May 07 '11 00:05

Anthony Honciano


People also ask

Which code snippet allows you to programmatically add a Textview to a LinearLayout?

Is setContentView(R. layout.

How do I add a scrollbar to LinearLayout?

I suggest you place your LinearLayout inside a ScrollView which will by default show vertical scrollbars if there is enough content to scroll. If you want the vertical scrollbar to always be shown, then add android:scrollbarAlwaysDrawVerticalTrack="true" to your ScrollView .


2 Answers

Something like the following should be what you need:

final int N = 10; // total number of textviews to add  final TextView[] myTextViews = new TextView[N]; // create an empty array;  for (int i = 0; i < N; i++) {     // create a new textview     final TextView rowTextView = new TextView(this);      // set some properties of rowTextView or something     rowTextView.setText("This is row #" + i);      // add the textview to the linearlayout     myLinearLayout.addView(rowTextView);      // save a reference to the textview for later     myTextViews[i] = rowTextView; } 
like image 131
Joseph Earl Avatar answered Oct 04 '22 18:10

Joseph Earl


You can add TextViews at runtime by following code below:

LinearLayout lLayout = (LinearLayout) findViewById(R.id.linearlayout2); // Root ViewGroup in which you want to add textviews for (int i = 0; i < 5; i++) {     TextView tv = new TextView(this); // Prepare textview object programmatically     tv.setText("Dynamic TextView" + i);     tv.setId(i + 5);     lLayout.addView(tv); // Add to your ViewGroup using this method } 
like image 32
jayrhd Avatar answered Oct 04 '22 18:10

jayrhd