将数据从 DialogFragment 传递到 ListFragment 中的 ArrayAdapter

Passing data from DialogFragment to ArrayAdapter in ListFragment

我有 ListFragment,其中每一行都有按钮,单击后打开 dialogFragment,用户可以在其中选择 10 个选项中的 1 个(它是 10 个选项的列表视图)。 我想将此选择保存在 SQLite 数据库中(已经完成)并在 dialogFragment 消失后立即在 ListFragment 的特定列表行中反映选择。怎么做?

我读了那篇文章:http://developer.android.com/…/basics/fr…/communicating.html 但不知道如何在我的案例中实现这个想法,因为在我的案例中,它是两个片段之间的通信,省略 Activity.

假设您正在显示来自 ListFragment 的对话框,您希望在用户单击“确定”时获得回调。在您的 Dialog 中创建一个片段可以实现的接口,然后在用户单击确定时调用它。

public class ConfirmDialog extends DialogFragment implements Dialog.OnClickListener {

public interface OnItemSelectedListener {
    void onItemSelected(final int itemId);
}

private OnItemSelectedListener mListener;

public ConfirmDialog() {
    //Empty constructor
}

@NonNull
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
    //Do your setup here.
    return new AlertDialog.Builder(getActivity())
            .setTitle("MyTitle")
            .setMessage("Pick one")
            .setPositiveButton(R.string.ok, this)
            .setNegativeButton(R.string.cancel, this)
            .setView(R.layout.my_list_view)
            .create();
}

public void setOnItemSelectedListener(final OnItemSelectedListener listener) {
    mListener = listener;
}

@Override
public void onClick(DialogInterface dialog, int which) {
    if (mListener != null && which == Dialog.BUTTON_POSITIVE) {
        mListener.onItemSelected(/*Get the currently selected item from your listview*/0);
    }
}

这会将信息传回您的 ListFragment,您可以在其中更新 SQL 并刷新列表以反映您所做的更改。

更新数据库后,您将需要更新列表适配器正在查看的列表,很可能是重新查询。然后您需要在适配器上调用 notifyDataSetChanged,它应该会刷新。