Search code examples
androidtextview

How can I add textview dynamically from arraylist?


Is it possible add textView in a relative layout dynamically, taking the information from an arraylist? I'll explain. For example I have a arralist with five words that I get from a database. I would then create 5 different textView in its layout. I can not use a listview because it is the user to choose the poszione of these TextView.

This is the code I was working, so I was able to create more TextView, but not from the array list. I also need to give different values ​​for the top margin at each TextView!

RelativeLayout rl = (RelativeLayout) findViewById(R.id.sundayRelativeLayout);
    TextView iv;
    RelativeLayout.LayoutParams params;

    

    float d = this.getResources().getDisplayMetrics().density;

    iv = new TextView(this);
    iv.setBackgroundColor(Color.YELLOW);
    int marginTopDip = 180; // margin in dips
    int marginHeightDips = 60; // margin in dips

    int height = (int)(marginHeightDips * d);
    int margintop = (int)(marginTopDip * d);
    params = new RelativeLayout.LayoutParams(500, height);
    params.topMargin = margintop;
    rl.addView(iv, params);



    iv = new TextView(this);
    iv.setBackgroundColor(Color.RED);
    params = new RelativeLayout.LayoutParams(30, 40);
    params.topMargin = 900;
    rl.addView(iv, params);

Solution

  • Create like this

    ArrayList<Integer> list=new ArrayList<Integer>();
    

    if your list size is 5

    for(int i=0;i<list.size();i++){
    TextView tv=new TextView(this);
    tv.setText(""+list.get(i));
    }