我有一個帶有 12 個 Spinner 的 Fragment,在用戶單擊按鈕之前我不需要執行任何操作。
我所有的 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);
uj5u.com熱心網友回復:
將所有微調器包裝在一個 ViewGroup 中(使用 LinearLayout 或 ConstraintLayout),然后在單擊按鈕時運行 for 回圈并呼叫getChildAt(loopIndex)該 ViewGroup。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
uj5u.com熱心網友回復:
一種可能性是創建一個 id 陣列來回圈:
int[] spinnerIds = new int[] {R.id.spinnerP2Type, R.id.spinnerP1Type);
for (int spinnerId : spinnerIds) {
Spinner spinner = getView().findViewById(spinnerId);
// etc.
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/327502.html
上一篇:springtools3(standalone)3.9.14版本發布程序中出現內部錯誤:“將Spring靜態匯入加載到Eclipse代碼輔助收藏夾
