fragment之间的信息交互——onActivityResult()不经过Activity

1.本文讲述如何fragment与fragment之间互传信息,不用使用Activity的onActivityResult()方法

核心思想:FirstFragment获取到SecondFragment的对象,然后调用SecondFragment的onActivityResult()方法

CrimeFragment.java

private static final int REQUEST_DATE = 0;
private static final String DIALOG_NAME = "dateDialog";
private Crime mCrime;

mDateBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                FragmentManager fm = getActivity().getSupportFragmentManager();
                DateDialog dateDialog = DateDialog.newInstance(mCrime.getDate());
             dateDialog.setTargetFragment(CrimeFragment.this,REQUEST_DATE);
//最重要的方法:获取Fragment对象
                dateDialog.show(fm,DIALOG_NAME);
            }
        });
//重写onActivityResult()方法
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); if (requestCode == REQUEST_DATE){ Date date = (Date)data.getSerializableExtra(EXTRA_NEW_DATE); mDateBtn.setText(date.toString()); mCrime.setDate(date); } }

DialogFragment.java

new AlertDialog.Builder(getActivity())
                .setView(v)
                .setTitle(R.string.setDate)
                .setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        if (getTargetFragment() == null)
                            return;
                        Intent intent = new Intent();
                        intent.putExtra(CrimeFragment.EXTRA_NEW_DATE,mDate);
                        getTargetFragment().onActivityResult(getTargetRequestCode(), Activity.RESULT_OK,intent);
//getTargetFragment()获取对象并调用onActivityResult方法
                    }
                })
                .create();

 

posted @ 2016-03-01 17:04  技术丶从积累开始  阅读(553)  评论(0编辑  收藏  举报