《Android编程权威指南(第三版)》第十二章挑战练习Demo下

《Android编程权威指南(第三版)》第十二章挑战练习Demo下

时间太紧,导致写得有点慢,现在来补上:

第12 章的第二个挑战练习难度的确有点大,但还好,弄懂了就好写了,按书上步骤来:

1.更改onCreateDialog(Bundle)为onCreateView():

public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {


        Calendar calendar = Calendar.getInstance();
        int year = calendar.get(Calendar.YEAR);
        int month = calendar.get(Calendar.MONTH);
        int day = calendar.get(Calendar.DAY_OF_MONTH);

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

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

        Ok = (Button) view.findViewById(R.id.date_ok);
        Ok.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                int year = mDatePicker.getYear();
                int month = mDatePicker.getMonth();
                int day = mDatePicker.getDayOfMonth();
                Date date = new GregorianCalendar(year, month, day).getTime();
                /**
                 * 将data的值传到intent中,以便回传给CrimeFragment
                 */
                Intent intent = new Intent();
                intent.putExtra(EXTRA_DATE, date);
                getActivity().setResult(Activity.RESULT_OK, intent);
                getActivity().finish();
            }
        });

        return view;
    }

2.创建一个activity托管fragment:

public class DateActivity extends SingleFragmentActivity {

    /**
     * 继承SingleFragmentActivity用来托管DatePickerFragment()
     * @return
     */
    protected Fragment createFragment(){
        return new DatePickerFragment();
    }

}

3.以startActivityForResult()打开活动:

mDateButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                /**
                 * 更改代码为以下代码,以startActivityForResult(intent, REQUEST_DATE);启动活动
                 * 而不是启动一个dialog
                 */
                Intent intent = new Intent(getActivity(), DateActivity.class);
                startActivityForResult(intent, REQUEST_DATE);
            }
        });

并用onActivityResult()接收返回的数据:

public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode != Activity.RESULT_OK) {
            return;
        }
        /**
         * 接收活动返回的data值
         */
        if (requestCode == REQUEST_DATE) {
            Date date = (Date) data.getSerializableExtra(DatePickerFragment.EXTRA_DATE);
            mCrime.setDate(date);
            updateDate();
        }
    }

其实主要步骤不是太多,这题的意义就在于搞懂这一章结尾的那些概念,项目源码:Demo

若有不足,敬请指教 :)

你可能感兴趣的:(Android)