Dynamically add textViews to a linearLayout

后端 未结 6 1348
孤独总比滥情好
孤独总比滥情好 2020-11-29 00:23

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 tex

6条回答
  •  爱一瞬间的悲伤
    2020-11-29 01:03

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

提交回复
热议问题