Search code examples
javaandroidandroid-studiotextviewandroid-linearlayout

Adding TextView to Layout programmatically using for loop


So I was following Google's Android Basics course from Udacity. In one of the lessons inside onCreate method they made ArrayList of Strings and added values from "one" to "ten". After that they made LinearLayout variable and with for loop added TextViews to that layout. This is how whole code looks like:

protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_numbers);

        ArrayList<String> words = new ArrayList<>();
        words.add("one");
        words.add("two");
        // ...
        words.add("ten");

        LinearLayout rootView = findViewById(R.id.root_view);

        for (int i = 0; i < words.size(); i++) {
            TextView wordView = new TextView(this);
            wordView.setText(words.get(i));
            rootView.addView(wordView);
        }
    }

They didn't explain, how exactly we can add ten TextViews to layout with same name "wordView" inside for loop?


Solution

  • As @javdromero said in the comment, wordView is just a reference for the TextView View Object. We are just creating a TextView object. Setting the text on it and adding it to the rootView. rootView is just a reference name for the LinearLayout in your example. None if the reference names will set the id for the View Objects. The scope of wordView is limited to every loop while doing the for loop iteration, once the index increments you are having another View Object reference being assigned to wordView.