如何获得多个旋转器值?



我有一个片段,有12个旋转器,我不需要执行任何操作,直到用户点击一个按钮。

我所有的Spinners看起来都是这样的。(只显示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"
/>

它们都有非常相似的名字,并且没有其他旋转器。是否有可能在循环中处理它们,而不是每个对象创建一个新对象?

Spinner SpinP1 = getView().findViewById(R.id.spinnerP1Type);
Spinner SpinP2 = getView().findViewById(R.id.spinnerP2Type);

在ViewGroup中包装所有的旋转器(使用LinearLayout或ConstraintLayout),然后当按钮被点击时,运行for循环并调用该ViewGroup上的getChildAt(loopIndex)。ViewGroup应该已经用findViewById(R.id.the_container_name)实例化了

下面的代码
<LinearLayout
android:id="@+id/spinner_container"
android:orientation="vertical"
`...` >
<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"
/>
</LinearLayout>

然后调用:

Linearlayout container = getView().findViewById(R.id.spinner_container);

for (int i = 0; i < container.getChildCount(); i++) {
View child = container.getChildAt(i);
if (child instanceof Spinner) {
Spinner spinner = (Spinner) child;
spinner.setOnItemSelectedListener(new SimpleOnItemSelectedListener());
}
}


/**
* Listener
*/
public class SimpleOnItemSelectedListener implements AdapterView.OnItemSelectedListener {

@Override
public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {

}

@Override
public void onNothingSelected(AdapterView<?> adapterView) {

}
}

注:SimpleOnItemSelectedListener实现AdapterView.OnItemSelectedListener

一种可能性是创建一个id数组来循环:

int[] spinnerIds = new int[] {R.id.spinnerP2Type, R.id.spinnerP1Type);
for (int spinnerId : spinnerIds) {
Spinner spinner = getView().findViewById(spinnerId);
// etc.
}