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",..... };
4
  • Why a String-array? Isn't it easier to create an android.R.id-array? Commented Nov 27, 2015 at 13:58
  • Like this? Commented Nov 27, 2015 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]) Commented Nov 27, 2015 at 14:01
  • Or using this method where you can say String spinnerId = "spinner_grade_" + i; Commented Nov 27, 2015 at 14:03

2 Answers 2

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]);
            }
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you very much. I got it.
1

use Butterknife library:

@Bind({ R.id.first_name, R.id.middle_name, R.id.last_name })
List<EditText> nameViews;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.