1

I'm new to android and creating an app that have 30 spinners that share same content. How can I create these objects inside a loop without writing 30 lines ?

Spinner spinner_grade_1 = (Spinner) findViewById(R.id.spinner_grade_1);
Spinner spinner_grade_2 = (Spinner) findViewById(R.id.spinner_grade_2);
......
Spinner spinner_grade_30 = (Spinner) findViewById(R.id.spinner_grade_20);

instead of that how can I create these objects inside a loop ? (I have created the following string array)

gradeBoxNames = new String[]{"spinner_grade_1", "spinner_grade_2",..... };
  • Why a `String`-array? Isn't it easier to create an [`android.R.id`](http://developer.android.com/reference/android/R.id.html)-array? – Kevin Cruijssen Nov 27 '15 at 13:58
  • Like [this](http://stackoverflow.com/a/4865350)? – AuroMetal Nov 27 '15 at 14:01
  • you can make `Spinner[] array;` and make another array of int ids like `int[] arr ={R.id.spinner_grade_1};` Now you can loop through these values like `array[i] = findviewbyid(arr[i])` – Syed Qasim Ahmed Nov 27 '15 at 14:01
  • Or using [this method](http://stackoverflow.com/a/10626635) where you can say `String spinnerId = "spinner_grade_" + i;` – AuroMetal Nov 27 '15 at 14:03

2 Answers2

2

1) Initialize array of Resource ids

 int[] ids = {R.id.spinner_grade_1,R.id.spinner_grade_2};
        Spinner[] spinners = new Spinner[ids.length];


    for(int i=0 ;i< ids.length;i++) {
               spinners[i] = (Spinner) findViewById(ids[i]);
            }
Syed Qasim Ahmed
  • 1,352
  • 13
  • 24
1

use Butterknife library:

@Bind({ R.id.first_name, R.id.middle_name, R.id.last_name })
List<EditText> nameViews;
Marcin Bortel
  • 1,190
  • 2
  • 14
  • 28