1

Scenario: My Activity contains a few buttons with ID: btn1, btn2 and so on. I want the code to access these buttons through loop counter. So, which of the below two approaches is more efficient? Thanks!

getChildAt():

for (int optionCounter = 0; optionCounter < bigNumber; optionCounter++) {   
        optionButton = (Button) buttonRelativeLayout.getChildAt(optionCounter); //Layout contains Buttons
        optionButton.setText("some text");   }

NOTE: buttonRelativeLayout was just introduced artificially to access Buttons by child number. Which otherwise doesn't serve any purpose.

getIdentifier():

 for (int optionCounter = 0; optionCounter < bigNumber; optionCounter++) {
   String buttonID = "btn" + optionCounter;
   int resID = getResources().getIdentifier(buttonID, "id", "com.sample.project");
   optionButton = ((Button) findViewById(resID));
   optionButton.setText("some text");   }

Note: use of getIdentifier function is discouraged. It is much more efficient to retrieve resources by identifier than by name -Developers Reference. And the reference document stops there.

Thanks again!

Johnny
  • 282
  • 1
  • 15
  • 1
    You're aware that you can programmatically set an id on a view? http://developer.android.com/reference/android/view/View.html#setId(int) You also have this way to generate unique ids: http://developer.android.com/reference/android/view/View.html#generateViewId%28%29 – JohanShogun Jul 24 '15 at 11:14
  • Thanks JohanShogun! But my question only concerns about accessing View in a loop using loop counter not setting ID or generating ID. – Johnny Jul 25 '15 at 07:24
  • In that case getChildAt is more efficient, it's a single look up while your other code uses multiple look ups. To be sure, take a times tamp before and after each look, that way you can know which is the most efficient. – JohanShogun Jul 25 '15 at 10:26
  • Thanks, JohanShogun! – Johnny Jul 25 '15 at 11:10

0 Answers0