在片段中显示 DatePickerDialog

我正在创建一个具有 EditText 的片段,当我单击它时,会出现一个 DatePickerDialog .. 但是每当我单击 EditText 时我的应用程序就会崩溃..


错误在这一行:


    return new DatePickerDialog(getActivity(), (DatePickerDialog.OnDateSetListener) getActivity(), year, month, day);

我的费用片段 Java 代码(仅限 datepick 代码):


@Nullable

    @Override

    public View onCreateView(final LayoutInflater inflater, final ViewGroup container,

                             Bundle savedInstanceState) {

        // Inflate the layout for this fragment

        View view = inflater.inflate(R.layout.fragment_expense, container, false);


            mDisplayDate = (EditText) view.findViewById(R.id.datePick);


            mDisplayDate.setOnClickListener(new View.OnClickListener(){

                @Override

            public void onClick(View v) {

                DialogFragment datePicker = new DatePickerFragment();

                datePicker.show(getFragmentManager(), "date picker");

            }

        });

        return view;

    }


    @Override

    public void onDateSet(DatePicker view, int year, int month, int dayOfMonth) {

        Calendar c = Calendar.getInstance();

        c.set(Calendar.YEAR, year);

        c.set(Calendar.MONTH, month);

        c.set(Calendar.DAY_OF_MONTH, dayOfMonth);

        String currentDate = DateFormat.getDateInstance().format(c.getTime());


        dates = Integer.toString(dayOfMonth);

        months = Integer.toString(month);

        years = Integer.toString(year);


        mDisplayDate.setText(currentDate);


    }

日期选择器片段 java


package com.example.admin.test2;


import android.app.DatePickerDialog;

import android.app.Dialog;

import android.os.Bundle;

import android.support.annotation.NonNull;

import android.support.annotation.Nullable;

import android.support.v4.app.DialogFragment;


import java.util.Calendar;


慕丝7291255
浏览 93回答 2
2回答

不负相思意

ExpenseFragment实现DatePickerDialog.OnDateSetListener,因此您需要使用getTargetFragment()而不是getActivity().return new DatePickerDialog(getActivity(), (DatePickerDialog.OnDateSetListener) getTargetFragment(), year, month, day);然后setTargetFragment在创建时使用DatePickerFragment.mDisplayDate.setOnClickListener(new View.OnClickListener(){    @Override    public void onClick(View v) {        DialogFragment datePicker = new DatePickerFragment();        datePicker.setTargetFragment(ExpenseFragment.this, 0);        datePicker.show(getFragmentManager(), "date picker");    }});

MYYA

侦听器是在您的父 Fragment 中实现的,而不是您的父 Activity,因此您必须替换getActivity()为getParentFragment()return new DatePickerDialog(getActivity(), (DatePickerDialog.OnDateSetListener) getParentFragment(), year, month, day);
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java