35

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!

Anthony Honciano
  • 1,683
  • 5
  • 24
  • 30
  • I would think you would want a listview or something similar rather than pushing in textviews... – jkhouw1 May 07 '11 at 00:37
  • I was reading that too, but I read there was some problems where people can't access the editText from the listView. And if I did manage to add editText into the list, how do I dynamically grab the data? – Anthony Honciano May 07 '11 at 00:39
  • There are issues with `EditText`s in `ListView`s. The first is a focus issue which can be solved (see http://stackoverflow.com/questions/2679948/focusable-edittext-inside-listview) but if you are using `EditText`s actually as list items rather than footer/headers then there is also the issue of view recycling - meaning you need to save the text of the `EditText` before it goes off-screen and gets recycled. – Joseph Earl May 07 '11 at 01:19

7 Answers7

74

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;
}
Joseph Earl
  • 23,351
  • 11
  • 76
  • 89
  • Cool! Will try this out, could this also be used for editText too? – Anthony Honciano May 07 '11 at 01:20
  • Yes, the same pattern will work for `EditText`s, any view type in fact! – Joseph Earl May 07 '11 at 01:21
  • 1
    Another question Joseph, how do I grab the editText value dynamically? just by doing myEditTextView[i] = editTextRow.... Log.d("MYTAG", "EditTextValue="+myEditTextView[1]);?? – Anthony Honciano May 07 '11 at 02:17
  • 1
    Well if you want the value of the `X`th `EditText` then it would be `String editTxtValue = myEditTextView[X].getText().toString()`. If you set the ID of each row to also be it's row number (something like `rowTextView.setId(i)` in the above example), then you can easily get the row number with `view.getId()` in an `OnClickListener` – Joseph Earl May 07 '11 at 02:25
  • @Joseph, I changed the views to EditText and now there's nothing appearing... any thoughts? – Anthony Honciano May 07 '11 at 02:51
  • @Joseph, neeeeevermind, I figured it out...developmentError :P Anyway, thank you for your answer! I would give you like 10+ ranking and a cupcake if possible :P – Anthony Honciano May 07 '11 at 03:00
  • 1
    how can you bind `OnClickListeners` to the elements created ? – Francisco Corrales Morales Jun 18 '14 at 02:44
16

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
}
Jeel Vankhede
  • 11,592
  • 2
  • 28
  • 58
jayrhd
  • 201
  • 2
  • 3
  • 3
    how can you bind `OnClickListeners` to the elements created ? – Francisco Corrales Morales Jun 18 '14 at 02:45
  • @FranciscoCorralesMorales Add onClickListener as beow, `LinearLayout lLayout = (LinearLayout) findViewById(R.id.linearlayout2); 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); tv.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { System.out.println("view item clicked"); } }); lLayout.addView(tv); // Add to your ViewGroup }` – rohit Oct 07 '20 at 10:09
3

I think this will be useful:

int j = 0;

context.getSystemService(Context.WINDOW_SERVICE);
WindowManager manager = (WindowManager) context
                        .getSystemService(Context.WINDOW_SERVICE);
Display display = manager.getDefaultDisplay();

for (int i = 0; i < tabsize; i++) {
    Tab tab = tabSet.get(i);
    if (i == selectedTabId)
        tab.setSelected(true);
    View view = tab.getView();

    TableRow.LayoutParams pCol = new TableRow.LayoutParams();
    pCol.width = display.getWidth() / tabSet.size();

    rowBottom.addView(view, pCol);
}
rikitikitik
  • 2,414
  • 2
  • 26
  • 37
Jabbir Basha
  • 455
  • 6
  • 7
3

Using ArrayList may help you add any number of TextViews dynamically. You may even want to delete a specific TextView from the parent linear layout. This is a memory efficient way. Following is a snippet.

ArrayList<TextView> mTextViewList = new ArrayList<>(); //empty list of TextViews

if(condition){ 
    /* can repeat several times*/

    //Create a temporary instance which will be added to the list
    final TextView mTextView = new TextView(this);

    //Add the instance to the ArrayList
    mTextViewList.add(mTextView);

    //Add view to the Parent layout in which you want to add your views
    mLinearLayout.addView(mTextView);
}

//Change the text of 6th(index:5) TextView which was added
mTextViewList.get(5).setText("My Text");

//Remove 2nd(index:1) TextView from the parent LinearLayout
mLinearLayout.removeView(mTextViewList.get(1));
backslashN
  • 2,795
  • 3
  • 15
  • 25
1

For me this is a solution.

// Set Variables

TextView t;
ArrayList<TextView> textViewArrayList;
LayoutInflater layoutInflater;
LinearLayout ll_itensobrigatorios

// Tell in your onCreate

layoutInflater = getLayoutInflater();
createViewItem(new String[]{"Fabio", "Santos", "Programador", "Natal"});

// This create view in layout

    private void createViewItem(String[] nomes) {
            textViewArrayList = new ArrayList<>();

            for(int i = 0; i < nomes.length; i++) {
                View vll = layoutInflater.inflate(R.layout.nomes_tec_item, ll_itensobrigatorios, false);
                t = (TextView) vll.findViewById(R.id.txt_tec_item);
                textViewArrayList.add(t);
                ll_itensobrigatorios.addView(vll);
            }

            for(int i = 0; i < textViewArrayList.size(); i++) {
                textViewArrayList.get(i).setText((i + 1) + " - " + nomes[i]);
            }
}
Programador
  • 133
  • 1
  • 5
0

So lets say you have created a linearlayout inside a .xml file like this:

<LinearLayout
    android:orientation="vertical"
    android:id="@+id/linear"
    android:layout_width="match_parent"
    android:layout_height="wrap_content">
</LinearLayout>

now the code to add 5 textviews dynamically

  LinearLayout linearLayout= (LinearLayout)findViewById(R.id.linear);      //find the linear layout
    linearLayout.removeAllViews();                              //add this too
    for(int i=0; i<5;i++){          //looping to create 5 textviews

        TextView textView= new TextView(this);              //dynamically create textview
        textView.setLayoutParams(new LinearLayout.LayoutParams(             //select linearlayoutparam- set the width & height
                ViewGroup.LayoutParams.MATCH_PARENT, 48));
        textView.setGravity(Gravity.CENTER_VERTICAL);                       //set the gravity too
        textView.setText("Textview: "+i);                                    //adding text
        linearLayout.addView(textView);                                     //inflating :)
    }
0

In Kotlin

val lLayout = findViewById<View>(R.id.l1) as LinearLayout

    for (i in 0..4) {
        val tv = TextView(this)
        tv.text = "TextView $i"
        tv.id = i + 5
        lLayout.addView(tv)
    }
Sandeep Pareek
  • 1,636
  • 19
  • 21