我一直在關注我的項目中使用DialogFragment的官方android developer docu和this one。因爲我必須將數據傳遞給DialogFragment才能創建多選列表,所以我通過newInstance
方法(傳遞項目)從MainActivity內部調用DialogFragment,並得到正確的結果。現在,我想傳遞另一個參數,即DialogFragment的數據,但它必須是可選的,因爲我不需要一直傳遞它。我有辦法實現這一目標嗎?Android DialogFragment newInstance可選參數
編輯:
所以我把文章從下面的意見,並創造了一個二傳手,並通過我希望傳遞給DiagramFragment的項目。它工作得很好,可悲的是它並沒有幫助我解決我的問題。我想傳遞第二個數據的原因是,我認爲,如果用戶打開DialogFragment並進行選擇,然後重新打開DialogFragment,他的最後選擇將消失。我想檢查他已經通過編程檢查過的複選框,將檢查一次傳回到DialogFragment,然後將正確的索引設置回mSelectedItems
- 但即使索引設置正確,複選框仍未選中。是否有解決方法?
static MyDialogFragment newInstance(int num) {
MyDialogFragment f = new MyDialogFragment();
// Supply num input as an argument.
Bundle args = new Bundle();
args.putInt("num", num);
f.setArguments(args);
return f;
}
...
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
mSelectedItems = 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
mSelectedItems.add(which);
} else if (mSelectedItems.contains(which)) {
// Else, if the item is already in the array, remove it
mSelectedItems.remove(Integer.valueOf(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 mSelectedItems 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();
}
標準也許 – 2017-01-01 18:46:39
剛剛通過null如何?當它不可用 –
@JawadLeWywadi可能嗎?如何使用setter函數 'DialogFragment newFragment = MyDialogFragment.newInstance(items);'然後'newFragment.setMySetter(value);'?喜歡這個 ?? – b101