从Dialog Fragment刷新EditText值

时间:2018-04-19 13:38:15

标签: android datepicker android-dialogfragment

我正在尝试从用户中选择特定日期,然后在EditText中显示它。我正在使用以下方法,其中在onDateSet()中从DatePickerDialog选择Date后,我正在更新EditText,但编辑文本永远不会更新(不显示所选值)pls。指导什么错误的代码?

public class CreateReport extends AppCompatActivity {
    EditText blockName;
    EditText eventDesc;
    public EditText eventDate;
    public EditText eventTime;
    EditText reporterName;
    EditText reporterCnic;
    public static Calendar userCalendar;
    private String Lat, Long;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_create_report);
//        final ActionBar ab = getSupportActionBar();
//        ab.setTitle("Create Reoprt");
        Bundle bundle = getIntent().getExtras();

        blockName = (EditText) findViewById(R.id.block_name);
        eventDate = (EditText) findViewById(R.id.ev_Date);
        eventTime = (EditText) findViewById(R.id.ev_Time);
        reporterName = (EditText) findViewById(R.id.reporter_name);
        reporterName.setText(AppSettings.getUserName());
        reporterCnic = (EditText) findViewById(R.id.reporter_cnic);
        reporterCnic.setText(AppSettings.getUserCnic());
        reporterName.setEnabled(false);
        reporterCnic.setEnabled(false);
        eventDesc = (EditText) findViewById(R.id.event_desc);
        eventDate.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showDatePickerDialog(v);
            }
        });
        eventTime.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showTimePickerDialog(v);
            }
        });
        if (bundle != null) {
            Lat = bundle.getString("lat");
            Toast.makeText(getContext(), "Latitude" + Lat, Toast.LENGTH_LONG).show();
            Long = bundle.getString("Long");
        }
    }

    public void showTimePickerDialog(View v) {
        TimePickerFragment newFragment = new TimePickerFragment();
        newFragment.setOnTimeSelectedListener(new TimePickerDialog.OnTimeSetListener() {
            @Override
            public void onTimeSet(TimePicker view, int hourOfDay, int minute) {

                String myFormat = "HH:mm";
                SimpleDateFormat sdf = new SimpleDateFormat(myFormat, Locale.US);
                Calendar cal = Calendar.getInstance();
                cal.set(hourOfDay, minute);

                String formattedTime = sdf.format(cal.getTime());
                eventTime.setText(formattedTime);
                Toast.makeText(CreateReport.this, "Time" + formattedTime, Toast.LENGTH_LONG).show();
            }
        });
        newFragment.show(getSupportFragmentManager(), "timePicker");
    }

    public void showDatePickerDialog(View v) {
        DatePickerFragment newFragment = new DatePickerFragment();
        newFragment.setOnDateSelectedListener(new DatePickerDialog.OnDateSetListener() {
            @Override
            public void onDateSet(DatePicker view, int year, int month, int dayOfMonth) {
                // Do something with the date chosen by the user
                String myFormat = "yyyy-MM-dd";
                SimpleDateFormat sdf = new SimpleDateFormat(myFormat, Locale.US);
                Calendar cal = Calendar.getInstance();
                cal.set(year, month, dayOfMonth);

                String formattedTime = sdf.format(cal.getTime());
                eventDate.setText(formattedTime);
                Toast.makeText(CreateReport.this, "Date" + formattedTime, Toast.LENGTH_LONG).show();
            }
        });
        newFragment.show(getSupportFragmentManager(), "datePicker");
    }













    public static class TimePickerFragment extends DialogFragment {

        TimePickerDialog.OnTimeSetListener mListener;

        public TimePickerFragment() {
            // Default constructor. Required
        }

        public void setOnTimeSelectedListener(TimePickerDialog.OnTimeSetListener listener) {
            mListener = listener;
        }

        @NonNull
        @Override
        public Dialog onCreateDialog(Bundle savedInstanceState) {
            // Use the current date as the default date in the picker
            final Calendar c = Calendar.getInstance();
            int hour = c.get(Calendar.HOUR_OF_DAY);
            int minute = c.get(Calendar.MINUTE);
            int sec = c.get(Calendar.SECOND);

            // Create a new instance of TimePickerDialog and return it
            return new TimePickerDialog(getContext(),mListener, hour, minute, true);
        }
    }


    public static class DatePickerFragment extends DialogFragment {

        DatePickerDialog.OnDateSetListener mListener;

        public DatePickerFragment() {
            // Default constructor. Required
        }

        public void setOnDateSelectedListener(DatePickerDialog.OnDateSetListener listener) {
            mListener = listener;
        }

        @NonNull
        @Override
        public Dialog onCreateDialog(Bundle savedInstanceState) {
            // Use the current date as the default date in the picker
            final Calendar c = Calendar.getInstance();
            int year = c.get(Calendar.YEAR);
            int month = c.get(Calendar.MONTH);
            int day = c.get(Calendar.DAY_OF_MONTH);

            // Create a new instance of DatePickerDialog and return it
            return new DatePickerDialog(getContext(), mListener, year, month, day);
        }
    }
}

XML CODE

<?xml version="1.0" encoding="utf-8"?>
<ScrollView
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical" >

        <LinearLayout
            android:id="@+id/crt_event_layout"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="vertical"
            android:layout_alignParentLeft="true"
            android:layout_alignParentStart="true"
            android:layout_alignParentTop="true">

            <EditText
                android:id="@+id/block_name"
                android:inputType="textAutoComplete"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:background="@drawable/loginfields_borders"
                android:hint="Block Name"
                android:padding="12dp"
                android:textColor="#a3a3a3"
                android:textSize="13sp" />

            <EditText
                android:id="@+id/ev_Date"
                android:inputType="datetime"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:background="@drawable/loginfields_borders"
                android:hint="Event Date"
                android:focusable="false"
                android:padding="12dp"
                android:textColor="#a3a3a3"
                android:textSize="13sp"
                android:onClick="showDatePickerDialog"/>

            <EditText
                android:id="@+id/ev_Time"
                android:inputType="datetime"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:background="@drawable/loginfields_borders"
                android:hint="Event Time"
                android:focusable="false"
                android:padding="12dp"
                android:textColor="#a3a3a3"
                android:textSize="13sp" />


            <EditText
                android:id="@+id/reporter_name"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_marginTop="10dp"
                android:background="@drawable/loginfields_borders"
                android:hint="Reporting Official"
                android:padding="12dp"
                android:textColor="#a3a3a3"
                android:textSize="13sp" />

            <EditText
                android:id="@+id/reporter_cnic"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_marginTop="10dp"
                android:background="@drawable/loginfields_borders"
                android:hint="Reporting Official"
                android:padding="12dp"
                android:textColor="#a3a3a3"
                android:textSize="13sp" />

            <EditText
                android:id="@+id/event_desc"
                android:inputType="textAutoComplete"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:background="@drawable/loginfields_borders"
                android:hint="Event Description"
                android:padding="12dp"
                android:textColor="#a3a3a3"
                android:textSize="13sp" />

        </LinearLayout>
    </RelativeLayout>

</ScrollView>

日志单击日期编辑文本后生成,并由此导致CreateReport活动的销毁

      04-19 21:30:16.281 28941-28941/? I/art: Late-enabling -Xcheck:jni
        Reinit property: dalvik.vm.checkjni= false
        04-19 21:30:16.517 28941-28941/com.example.aiousecurityapplication W/System: ClassLoader referenced unknown path: /data/app/com.example.aiousecurityapplication-1/lib/arm64
        04-19 21:30:16.534 28941-28941/com.example.aiousecurityapplication I/InstantRun: starting instant run server: is main process
        04-19 21:30:16.563 28941-28941/com.example.aiousecurityapplication I/HwCust: Constructor found for class android.app.HwCustActivityImpl
        04-19 21:30:16.614 28941-28941/com.example.aiousecurityapplication W/art: Before Android 4.1, method android.graphics.PorterDuffColorFilter android.support.graphics.drawable.VectorDrawableCompat.updateTintFilter(android.graphics.PorterDuffColorFilter, android.content.res.ColorStateList, android.graphics.PorterDuff$Mode) would have incorrectly overridden the package-private method in android.graphics.drawable.Drawable
        04-19 21:30:16.901 28941-28941/com.example.aiousecurityapplication W/PhoneWindow: Previously focused view reported id 2131296398 during save, but can't be found during restore.
        04-19 21:30:16.907 28941-28941/com.example.aiousecurityapplication I/HwSecImmHelper: mSecurityInputMethodService is null
        04-19 21:30:16.911 28941-28941/com.example.aiousecurityapplication I/HwPointEventFilter: do not support AFT because of no config
        04-19 21:30:16.988 28941-28941/com.example.aiousecurityapplication I/HwCust: Constructor found for class android.net.HwCustConnectivityManagerImpl
        04-19 21:30:17.022 28941-28941/com.example.aiousecurityapplication E/RecyclerView: No adapter attached; skipping layout
        04-19 21:30:17.022 28941-28964/com.example.aiousecurityapplication I/OpenGLRenderer: Initialized EGL, version 1.4
        04-19 21:30:17.033 28941-28964/com.example.aiousecurityapplication W/linker: /vendor/lib64/libhwuibp.so: unused DT entry: type 0xf arg 0xe3a
        04-19 21:30:17.111 28941-28941/com.example.aiousecurityapplication W/art: Before Android 4.1, method int android.support.v7.widget.ListViewCompat.lookForSelectablePosition(int, boolean) would have incorrectly overridden the package-private method in 
        android.widget.ListView
        04-19 21:30:17.208 28941-28941/com.example.aiousecurityapplication E/RecyclerView: No adapter attached; skipping layout
        04-19 21:30:18.734 28941-28946/com.example.aiousecurityapplication I/art: Do partial code cache collection, code=23KB, data=29KB
        04-19 21:30:18.735 28941-28946/com.example.aiousecurityapplication I/art: After code cache collection, code=23KB, data=29KB
        Increasing code cache capacity to 128KB

4 个答案:

答案 0 :(得分:1)

请尝试以下代码。

想法是实现DatePickerDialog.OnDateSetListener并将其传递给DialogFragment。 不要将时间存储在静态字段中,因为您可以在用户选择日期(public void onDateSet(DatePicker view, int year, int month, int day))时调用的Dialog方法中直接访问此信息。

由于在“活动”中实施了侦听器,您可以访问EventDate字段。

顺便说一句,我已将其重命名为mEventDate,因为字段/变量不应以首字母命名。使用'm'作为起始字母命名字段是最佳做法,因为它将类变量与局部变量区分开来。

另一个改进应该是将DatePickerFragment放在一个单独的类文件中,因为它令人困惑。每个人(包括我自己)都认为你可以直接访问EventDate字段,因为我们在读取代码时没有注意到静态类。

<强> EDITED

public class CreateReportActivity extends AppCompatActivity {

    public EditText mEventDate;
    private String Lat, Long;

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

        mEventDate = (EditText) findViewById(R.id.ev_Date);
    }

    public void showDatePickerDialog(Context context, View v) {
        DatePickerFragment newFragment = new DatePickerFragment();
        newFragment.setOnDateSelectedListener(new DatePickerDialog.OnDateSetListener() {
            @Override
            public void onDateSet(DatePicker view, int year, int month, int dayOfMonth) {
                // Do something with the date chosen by the user
                String myFormat = "yyyy-MM-dd";
                SimpleDateFormat sdf = new SimpleDateFormat(myFormat, Locale.US);
                Calendar cal = Calendar.getInstance();
                cal.set(year, month, dayOfMonth);

                String formattedTime = sdf.format(cal.getTime());
                mEventDate.setText(formattedTime);
                Toast.makeText(context, "Date" + formattedTime, Toast.LENGTH_LONG).show();
            }
        });
        newFragment.show(getSupportFragmentManager(), "datePicker");
    }

    public static class DatePickerFragment extends DialogFragment {

        DatePickerDialog.OnDateSetListener mListener;

        public DatePickerFragment() {
            // Default constructor. Required
        }

        public void setOnDateSelectedListener(DatePickerDialog.OnDateSetListener listener) {
            mListener = listener;
        }

        @NonNull
        @Override
        public Dialog onCreateDialog(Bundle savedInstanceState) {
            // Use the current date as the default date in the picker
            final Calendar c = Calendar.getInstance();
            int year = c.get(Calendar.YEAR);
            int month = c.get(Calendar.MONTH);
            int day = c.get(Calendar.DAY_OF_MONTH);

            // Create a new instance of DatePickerDialog and return it
            return new DatePickerDialog(getContext(), mListener, year, month, day);
        }
    }
}

答案 1 :(得分:0)

它可以通过多种方式实现。我推荐第一个,您可以根据需要自定义OnDateSelected界面。并从任何班级调用日期选择器。

public class CreateReport extends AppCompatActivity {
    public EditText EventDate;
    public static Calendar usercalendar;
    private String Lat, Long;

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

        EventDate = (EditText) findViewById(R.id.ev_Date);


    }
    public void showDatePickerDialog(View v) {
        DialogFragment newFragment = new DatePickerFragment(new DatePickerFragment.OnDateSelected() {
            @Override
            public void onSelected(String date) {
                EventDate.setText(date);
            }
        });
        newFragment.show(getSupportFragmentManager(), "datePicker");
    }
    public static class DatePickerFragment extends DialogFragment
            implements DatePickerDialog.OnDateSetListener {
        Context context;

        OnDateSelected onDateSelected;

        public DatePickerFragment(OnDateSelected onDateSelected) {
            this.onDateSelected = onDateSelected;
        }

        interface OnDateSelected{
            void onSelected(String date);
        }

        @Override
        public Dialog onCreateDialog(Bundle savedInstanceState) {
            // Use the current date as the default date in the picker
            final Calendar c = Calendar.getInstance();
            int year = c.get(Calendar.YEAR);
            int month = c.get(Calendar.MONTH);
            int day = c.get(Calendar.DAY_OF_MONTH);
            usercalendar.set(year, month, day);

            // Create a new instance of DatePickerDialog and return it
            return new DatePickerDialog(getActivity(), this, year, month, day);
        }

        public void onDateSet(DatePicker view, int year, int month, int day) {
            // Do something with the date chosen by the user
            String myFormat = "yyyy-MM-dd";
            SimpleDateFormat sdf = new SimpleDateFormat(myFormat, Locale.US);

            View dialogName = getActivity().getLayoutInflater().inflate(R.layout.activity_create_report, null);
            ((EditText) dialogName.findViewById(R.id.ev_Date)).setText(sdf.format(usercalendar.getTime()));
            Toast.makeText(getContext(), "Date" + sdf.format(usercalendar.getTime()), Toast.LENGTH_LONG).show();
            if (onDateSelected!=null) onDateSelected.onSelected(sdf.format(usercalendar.getTime())); 
        }
    }
}

public class CreateReport extends AppCompatActivity {
    public EditText EventDate;
    public static Calendar usercalendar;
    private String Lat, Long;

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

        EventDate = (EditText) findViewById(R.id.ev_Date);


    }
    public void showDatePickerDialog(View v) {
        DatePickerFragment newFragment = new DatePickerFragment(EventDate);
        newFragment.setEditText(EventDate);
        newFragment.show(getSupportFragmentManager(), "datePicker");
    }
    public static class DatePickerFragment extends DialogFragment
            implements DatePickerDialog.OnDateSetListener {
        Context context;
        private EditText editText;

        public void setEditText(EditText editText) {
            this.editText = editText;
        }

        interface OnDateSelected{
            void onSelected(String date);
        }

        @Override
        public Dialog onCreateDialog(Bundle savedInstanceState) {
            // Use the current date as the default date in the picker
            final Calendar c = Calendar.getInstance();
            int year = c.get(Calendar.YEAR);
            int month = c.get(Calendar.MONTH);
            int day = c.get(Calendar.DAY_OF_MONTH);
            usercalendar.set(year, month, day);

            // Create a new instance of DatePickerDialog and return it
            return new DatePickerDialog(getActivity(), this, year, month, day);
        }

        public void onDateSet(DatePicker view, int year, int month, int day) {
            // Do something with the date chosen by the user
            String myFormat = "yyyy-MM-dd";
            SimpleDateFormat sdf = new SimpleDateFormat(myFormat, Locale.US);

            View dialogName = getActivity().getLayoutInflater().inflate(R.layout.activity_create_report, null);
            ((EditText) dialogName.findViewById(R.id.ev_Date)).setText(sdf.format(usercalendar.getTime()));
            Toast.makeText(getContext(), "Date" + sdf.format(usercalendar.getTime()), Toast.LENGTH_LONG).show();
            if (editText !=null) editText .setText(sdf.format(usercalendar.getTime()));
        }
    }
}

答案 2 :(得分:0)

通常使用EventDate.setText(sdf.format(usercalendar.getTime()));

它的工作正常。

答案 3 :(得分:0)

private void getDatePickerPOP() {

    final Calendar calendar = Calendar.getInstance();
    int mDay = calendar.get(Calendar.DAY_OF_MONTH);
    int mMonth = calendar.get(Calendar.MONTH);
    int mYear = calendar.get(Calendar.YEAR);

    DatePickerDialog mDatePicker = new DatePickerDialog(ViewersList.this, new DatePickerDialog.OnDateSetListener() {
        public void onDateSet(DatePicker datepicker, int selectedyear, int selectedmonth, int selectedday) {

            Calendar calander2 = Calendar.getInstance();
            calander2.setTimeInMillis(0);
            calander2.set(selectedyear, selectedmonth, selectedday, 0, 0, 0);
            java.util.Date SelectedDate = (java.util.Date) calander2.getTime();
            DateFormat dateformat_US = DateFormat.getDateInstance(DateFormat.MEDIUM, Locale.US);
            String StringDateformat_US = dateformat_US.format(SelectedDate);
            EventTextView.setText(StringDateformat_US);
        }
    }, mYear, mMonth, mDay);
    mDatePicker.getDatePicker().setMaxDate(System.currentTimeMillis() + 1000);
    mDatePicker.setTitle("Select date");
    mDatePicker.show();
}