我有一个使用 DialogFragment
的 Activity 。这是我第一次实现对话框,因此我使用 newInstance
创建此对话框(如多个指南中所建议的)需要是静态的;因此,我的DialogFragment
也是静态的。
我使用List<String>
要存储和填充对话框,但要做到这一点,需要我在 Activity 中也将此列表声明为静态。 Afaik,在 Java 中保存静态变量是不好的做法。那么就我的情况而言,我可以避免这种情况吗?如何?
换句话说,如何将数据从我的 Activity 传递到对话框而不是静态的?请注意,我需要经常修改此列表。
我创建对话框如下:
FragmentManager fm = getSupportFragmentManager();
PickDisplayDialogFragment alertDialog = PickDisplayDialogFragment.newInstance("Displays");
alertDialog.show(fm, "fragment_alert");
我的 newInstance 看起来像:
public static PickDisplayDialogFragment newInstance(String title) {
PickDisplayDialogFragment frag = new PickDisplayDialogFragment();
Bundle args = new Bundle();
args.putString(DIALOG_TITLE, title);
frag.setArguments(args);
return frag;
}
编辑:我使用 getList() 获取列表并将其与dialog.setItems() 一起使用(通过转换为数组):
@NonNull
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
String title = getArguments().getString(DIALOG_TITLE);
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(getActivity());
alertDialogBuilder.setTitle(title);
alertDialogBuilder.setItems(getList(), new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
createIntentViewDisplay(which);
}
});
return alertDialogBuilder.create();
}
最佳答案
只需使用 putStringArrayList() 函数将字符串放入 Bundle 中即可。 Android documentation
关于java - 在 Android 对话框中使用列表 - 如何避免静态?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37812177/