Android在Dialog 2的Dialog 1中设置了Text?

时间:2015-03-02 22:58:01

标签: android android-dialog

我有2个对话框。一个是普通输入对话框,第二个是DatePickerDialog。我想要做的是设置其中一个TextView的内容是DatePickerDialog中所选日期的第一个对话框,如下所示:

对话1:

public void showEventDialog() {
    dialog = new Dialog(MainActivity.context);
    dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
    dialog.setContentView(R.layout.post_event_dialog);
    dialog.getWindow().setBackgroundDrawableResource(android.R.color.transparent);

    // VIEWS:
    ...

    dateText = (TextView) dialog.findViewById(R.id.eventdate);
    dateText.setTypeface(MainActivity.textMain);
    dateText.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            showDateDialog();
        }
    });

    ...

    dialog.show();
}

AND DIALOG 2:

 public void showDateDialog() {
    Calendar newCalendar = Calendar.getInstance();
    fromDatePickerDialog = new DatePickerDialog(MainActivity.context, new DatePickerDialog.OnDateSetListener() {
        public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
            dateText.setText("Test");
        }

    }, newCalendar.get(Calendar.YEAR), newCalendar.get(Calendar.MONTH), newCalendar.get(Calendar.DAY_OF_MONTH));
    fromDatePickerDialog.show();
}

但是,当我尝试在第一个对话框中设置TextView的Text时,我得到一个NullPointer异常。我该怎么做呢?我知道这一定是一个非常微不足道的问题,但我根本无法绕过它。 谢谢

1 个答案:

答案 0 :(得分:1)

因为,在第二个对话框中没有TextView dateText的引用,因为它总是 NULL (仅在从第一个对话框初始化后才可用)

只需将dateText引用传递给showDialog()赞,

    public void showDateDialog(final TextView dateText) {
        Calendar newCalendar = Calendar.getInstance();
        fromDatePickerDialog = new DatePickerDialog(MainActivity.context, new DatePickerDialog.OnDateSetListener() {
            public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
                dateText.setText("Test");
            }

    }, newCalendar.get(Calendar.YEAR), newCalendar.get(Calendar.MONTH), newCalendar.get(Calendar.DAY_OF_MONTH));
    fromDatePickerDialog.show();
} 

并打电话,

showDateDialog(dateText);