Search code examples
javaandroidfindviewbyid

How to define and set TextView in a for loop to concise the code?


I want to make the below code concise. It has repetition of similar kind of calls. I tried LinearView and GetChildCount method but It does not give me proper results, I might have misunderstood how to define these in loop using Childs Or other method.

Can any one help ?

tv1 = (EditText) findViewById(R.id.tv1);
tv2 = (EditText) findViewById(R.id.tv2);
tv3 = (EditText) findViewById(R.id.tv3);
// ...
// ... and so on till
// ...
tv25 = (EditText) findViewById(R.id.tv25);

// Similarly
tv1.setText(stall);
// ... till ...
tv25.setText(stall);

Solution

  • Use this:

        //create an array of ids
        int[] editextIDs = {R.id.tv1
                ,R.id.tv2
                ,R.id.tv3
                ,R.id.tv4
                ,R.id.tv5
                ,R.id.tv6
                ,R.id.tv7
                ,R.id.tv8
                ,R.id.tv9
                ,R.id.tv10
                ,R.id.tv11
                ,R.id.tv12
                ,R.id.tv13
                ,R.id.tv14
                ,R.id.tv15
                ,R.id.tv16
                ,R.id.tv17
                ,R.id.tv18
                ,R.id.tv19
                ,R.id.tv20
                ,R.id.tv21
                ,R.id.tv22
                ,R.id.tv23
                ,R.id.tv24
                ,R.id.tv25
        };
        //create an arraylist of 25 editTexts
        ArrayList<EditText> editTexts = new ArrayList<>();
        //fill the array
        for(int i = 0; i < 25 ;i++)
        {
            editTexts.add(i,(EditText) findViewById(editextIDs[i]));
        }
        //set the texts
        for(int i = 25; i <25 ;i++)
        {
            editTexts.get(i).setText(stall);
        }
    

    This may seem a lot of cut and pasting, but i created the ,R.id.tvX with excel. To do this, you write

    ,R.id.tv1

    and then drag it till you got 25 fields.

    Also, if you want to clean your code a bit, you may create a class in which you paste the array creation part and make the variable static. For example if you call the class EditTextArrayHandler, you would get the array like this:

    int[] editextIDs = EditTextArrayHandler.editTextIDs;
    

    Hope it helps.