Find TextView which was created programmatically?

Issue

How can I find those TextView’s another function on same class?
I will use setText(), serBackgroundColor() after create.

This code part is on CreateDesign() and this func calling onCreate():

public class MainActivity extends AppCompatActivity {

private LinearLayout linearLayout;
private TextView textView;

public void CreateDesign(){

   linearLayout = (LinearLayout) findById(R.id.linearLayout);

   for(int i = 1; i <= 5; i++){
        textView = new TextView(this);
        textView.setId(i);
        textView.setText(i + ". TextView");
        
        linearLayout.addView(textView);
    }
}

Solution

Well you don’t necessarily need to use id here, There are several ways to achieve this:

1.

TextView textView = (TextView) linearLayout.findViewById(i);

i is what you set before from 1 to 5.

2.

TextView textView = (TextView) linearLayout.getChildAt(i);

i here is the number of set item, for instance i=0 is the first textView you added using addView() method.

Answered By – Steve Moretz

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published