我在 Android Studio 中作業時一直在研究如何創建多選復選框對話框,自然而然地通過查看 android 開發人員頁面開始并遇到了本指南。他們展示的代碼示例是這樣的:
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
selectedItems = new ArrayList(); // Where we track the selected items
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
// Set the dialog title
builder.setTitle(R.string.pick_toppings)
// Specify the list array, the items to be selected by default (null for none),
// and the listener through which to receive callbacks when items are selected
.setMultiChoiceItems(R.array.toppings, null,
new DialogInterface.OnMultiChoiceClickListener() {
@Override
public void onClick(DialogInterface dialog, int which,
boolean isChecked) {
if (isChecked) {
// If the user checked the item, add it to the selected items
selectedItems.add(which);
} else if (selectedItems.contains(which)) {
// Else, if the item is already in the array, remove it
selectedItems.remove(which);
}
}
})
// Set the action buttons
.setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int id) {
// User clicked OK, so save the selectedItems results somewhere
// or return them to the component that opened the dialog
...
}
})
.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int id) {
...
}
});
return builder.create();
}
現在我有興趣看的是這個:
.setMultiChoiceItems(R.array.toppings, null,
new DialogInterface.OnMultiChoiceClickListener() {
@Override
public void onClick(DialogInterface dialog, int which,
boolean isChecked) {
if (isChecked) {
// If the user checked the item, add it to the selected items
selectedItems.add(which);
} else if (selectedItems.contains(which)) {
// Else, if the item is already in the array, remove it
selectedItems.remove(which);
}
}
})
現在我在這里遺漏了一些東西,或者這里的代碼有錯誤嗎?我的意思是不會呼叫remove()inselectedItems.remove(which)解釋which為 anint而不是 anObject從而洗掉int存盤在指定位置的元素which而不是int從陣列中洗掉實際?這是我在閱讀代碼時假設會發生的情況,以及當我嘗試運行導致IndexOutOfBoundsError.
然而,由于代碼來自谷歌本身提供的資源,我覺得很可能是我遺漏了一些東西。如果是這樣的話,我錯過了什么?如果情況并非如此,并且實際上代碼中存在錯誤,那么我很抱歉,因為該主題似乎不再與 stackoverflow 相關。
當談到如何解決我遇到的問題時,這不是問題,因為我意識到我可以簡單地執行類似selectedItems.remove((Integer) which)或 的操作selectedItems.remove(Integer.valueOf(which))。我只是對正在發生的事情感到困惑。
uj5u.com熱心網友回復:
你的診斷是正確的。給定兩個多載List.remove(int)和List.remove(Object)一個帶int引數的呼叫,Java 編譯器將靜態決議對第一個多載而不是第二個1的呼叫。但是這個背景關系的語意需要第二個多載;即按值而不是按位置移除。
這是檔案中的錯誤。通過正常渠道舉報...
1 - 這在JLS 15.12 中指定。規范的這一部分既復雜又技術性,但要點是編譯器首先查找與引數型別嚴格匹配的多載;即沒有裝箱或拆箱。如果沒有嚴格匹配,它只考慮非嚴格匹配。非正式地,int->int是比int->的“更接近匹配” Object,其中涉及裝箱 toInteger后跟參考擴展到Object.
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/396676.html
