从Dialog中将数据添加到RecyclerView列表项

时间:2017-08-24 16:41:01

标签: android android-recyclerview android-alertdialog

我试图获取用户在对话框中输入的数据,并将该数据放入我为RecyclerView创建的自定义列表项中的文本字段中。这是我的实施:

public class AssignmentActivity extends AppCompatActivity {
    ...

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_assignment);

        ...

        FloatingActionButton assignmentAddButton = (FloatingActionButton) findViewById(R.id.assignment_add_button);

        assignmentAddButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                editCourseInfoDialog();
            }
        });

    }

    private void editCourseInfoDialog() {
        LayoutInflater inflater = LayoutInflater.from(AssignmentActivity.this);
        View dialogLayout = inflater.inflate(R.layout.assignment_edit_dialog, null);
        AlertDialog.Builder dialog = new AlertDialog.Builder(AssignmentActivity.this);
        dialog.setView(dialogLayout);

        final TextView name = (TextView) dialogLayout.findViewById(R.id.assignmentNameView);
        final TextView mark = (TextView) dialogLayout.findViewById(R.id.assignmentMarkView);
        final TextView overallMark = (TextView) dialogLayout.findViewById(R.id.assignmentOverallMarkView);
        final TextView weight = (TextView) dialogLayout.findViewById(R.id.assignmentWeightView);

        dialog.setPositiveButton("OK", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                assignment.setName(String.valueOf(name.getText()));
                assignment.setMark(Double.valueOf(mark.getText() + ""));
                assignment.setMarkOutOf(Double.valueOf(overallMark.getText() + ""));
                assignment.setPercentage(Double.valueOf(weight.getText() + ""));
                assignmentAdapter.notifyDataSetChanged();
                dialog.dismiss();
            }
        });

        dialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.cancel();
            }
        });
        dialog.show();
    }
}

这个问题是当我单击OK时,对话框关闭,所有数据都被销毁。我无法找到将此数据粘贴到列表项中的方法,因为每次尝试都会导致它们丢失。

1 个答案:

答案 0 :(得分:1)

您可以使用RxJAVARxBindings。它会让一切变得更加轻松。

  • 创建返回Observable的函数
  • 在功能
  • 中显示对话框
  • 对话框完成后调用observable.onNext()

      -
  • 订阅该功能(使用fn()。subscribe(...))
  • 在订阅功能
  • 中捕获值
  • 将其添加到您的recyclerview