欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Android Criminal实例--(5)对话框的使用及fragment的数据传递

程序员文章站 2022-06-08 12:16:19
...

fragment的数据传递还不是很懂……先把对话框记录一下

这里使用DialogFragment来封装AlertDialog,这样可以随时建立,不会销毁。

dialog 的xml文件:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">
    <DatePicker
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/date_picker"
        android:calendarViewShown="false"
        />

</LinearLayout>
//显示的是老式日历
android:datePickerMode="spinner"

DatePickerFragment代码:

不是很懂。。下去还要继续学习

public class DatePickerFragment extends DialogFragment {

    public static final String ARG_DATE = "arg_date";
    private DatePicker mDatePicker;
    public static final String EXTRA_DATE="com.apple.DatePaickerFragment.date";

    @NonNull
    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState) {

        Date date=(Date)getArguments().getSerializable(ARG_DATE);
        Calendar calendar=Calendar.getInstance();
        calendar.setTime(date);
        int year=calendar.get(Calendar.YEAR);
        int month=calendar.get(Calendar.MONTH);
        int day=calendar.get(Calendar.DAY_OF_MONTH);

        View mView=LayoutInflater.from(getActivity()).inflate(R.layout.dialog_date,null);

        mDatePicker=(DatePicker)mView.findViewById(R.id.date_picker);
        mDatePicker.init(year,month,day,null);

        return new AlertDialog.Builder(getActivity())
                .setView(mView)
                .setTitle(R.string.date_crime)
                .setPositiveButton("ok", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        int year=mDatePicker.getYear();
                        int day=mDatePicker.getDayOfMonth();
                        int month=mDatePicker.getMonth();
                        Date date=new GregorianCalendar(year,month,day).getTime();
                        sendRequest(Activity.RESULT_OK,date);
                    }
                })
                .create();
    }

    public static DatePickerFragment newInstance(Date date){
        Bundle args=new Bundle();
        args.putSerializable(ARG_DATE,date);

        DatePickerFragment fragment=new DatePickerFragment();
        fragment.setArguments(args);
        return fragment;
    }

    private void sendRequest(int resultCode,Date date){
        if(getTargetFragment()==null){
            return;
        }
        Intent intent=new Intent();
        intent.putExtra(EXTRA_DATE,date);
        getTargetFragment().onActivityResult(getTargetRequestCode(),resultCode,intent);
    }
}

修改后的button点击事件为:
Android Criminal实例--(5)对话框的使用及fragment的数据传递
Android Criminal实例--(5)对话框的使用及fragment的数据传递
数据传递但是没看到效果。。。不知道哪里有问题

相关标签: android