I have a Fragment with 12 Spinners and I don’t need to perform any action until the user click on a button.
All my Spinners looks like this.(Showing only 2)
<Spinner
android:id="@+id/spinnerP1Type"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
style="@style/spinner_style"
android:entries="@array/powerTypes"
android:gravity="top"
/>
<Spinner
android:id="@+id/spinnerP2Type"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
style="@style/spinner_style"
android:entries="@array/powerTypes"
android:gravity="top"
/>
All of them have pretty similar name, and there’s no other spinners.
Is possible to process them in a loop instead of creating one new object by each one?
Spinner SpinP1 = getView().findViewById(R.id.spinnerP1Type);
Spinner SpinP2 = getView().findViewById(R.id.spinnerP2Type);
2
Answers
Wrap all the spinners in a ViewGroup (use either LinearLayout or ConstraintLayout) and then when the button is clicked, run a for loop and call
getChildAt(loopIndex)
on that ViewGroup. The ViewGroup should already have been instantiated withfindViewById(R.id.the_container_name)
The code below
Then call:
Note:
SimpleOnItemSelectedListener
implementsAdapterView.OnItemSelectedListener
One possibility is to create an array of ids to loop over: