Fragment数据传递与数据回显

Fragment数据传递

Fragment与Fragment之间数据传递

Fragment间数据的传递,是通过setArguments()和getArguments()这两个方法来进行实现

  • 传递数据

    Bundle bundle = new Bundle();
    bundle.putString("DataTransferFragment", "DataTransferInDifferentFragment");
    DataTransferFragment fragment = DataTransferFragment.newInstance(bundle);
                    fragment.show(getFragmentManager(),"DataTransferFragment");
  • 接收数据

    public class DataTransferFragment extends DialogFragment {
    
        private AlertDialog dialog;
        private String bundleString;
    
        public static DataTransferFragment newInstance(Bundle bundle) {
            DataTransferFragment fragment = new DataTransferFragment();
            fragment.setArguments(bundle);
            return fragment;
        }
    
    
        @Override
        public void onCreate(@Nullable Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            Bundle bundle = getArguments();
            if (bundle != null) {
                bundleString = bundle.getString("DataTransferFragment");
            }
        }
    
        @NonNull
        @Override
        public Dialog onCreateDialog(Bundle savedInstanceState) {
    
            TextView textView = new TextView(getActivity());
            textView.setText(bundleString);
            dialog = new AlertDialog.Builder(getActivity())
                    .setView(textView)
                    .create();
    
            return dialog;
        }
    }

Fragment与Activity之间数据传递

官方推荐Fragment与Activity之间数据传递的实现方式:接口回调

  • 接口定义

    /**
     * 确认事件回调
     */
    public interface OnConfirmClickListener {
        public void onConfirmClick(String userName, String password);
    }
    • Fragment代码
    public class TestDialogFragment extends DialogFragment {
    
        private AlertDialog dialog;
        private OnConfirmClickListener mListener;
    
        @Override
        public void onAttach(Context context) {
            super.onAttach(context);
            mListener = (OnConfirmClickListener) context;
        }
    
        @NonNull
        @Override
        public Dialog onCreateDialog(Bundle savedInstanceState) {
    
            View view = LayoutInflater.from(getActivity()).inflate(R.layout.fragment_test_dialog, null);
    
            dialog = new AlertDialog.Builder(getActivity())
                    .setView(view)
                    .create();
            Button cancel = (Button) view.findViewById(R.id.btn_cancel);
            Button confirm = (Button) view.findViewById(R.id.btn_confirm);
            final EditText mUserName = (EditText) view.findViewById(R.id.et_userName);
            final EditText mPassword = (EditText) view.findViewById(R.id.et_password);
            cancel.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    dialog.dismiss();
                }
            });
    
            confirm.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    mListener.onConfirmClick(mUserName.getText().toString(), mPassword.getText().toString());
                    dialog.dismiss();
                }
            });
    
            return dialog;
        }
    
        /**
         * 确认事件回调
         */
        public interface OnConfirmClickListener {
            public void onConfirmClick(String userName, String password);
        }
    
    }

    注意:上面代码中的onAttach()是关键点,在该方法中Fragment与Activity建立了关联关系

Fragment数据回显

有这样一个应用场景,从FragmentA跳转到FragmentB中,FragmentB经过编辑后,修改了FragmentA中的数据,这种场景分为以下两种情况

同一个Activity中,Fragment之间数据回显

  • FragmentA代码

    public class ContentFragment extends Fragment {
    
        public static final int REQUEST_CODE = 0x001;
        public static final int RESULT_CODE = 0x101;
        public static final String CONTENT_FRAGMENT = ContentFragment.class.getSimpleName();
        private TextView content;
    
        public static ContentFragment newInstance() {
            return new ContentFragment();
        }
    
        @Nullable
        @Override
        public View onCreateView(final LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
            final EditFragment editFragment = EditFragment.newInstance();
            View view = inflater.inflate(R.layout.fragment_content, container, false);
            content = (TextView) view.findViewById(R.id.tv_content);
            Button differentActivity = (Button) view.findViewById(R.id.btn_different_activity);
            Button button = (Button) view.findViewById(R.id.btn_button);
            button.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    //当一个Fragment启动另外一个Fragment时,setTargetFragment()设置该方法后,
                    //目标Fragment可以将数据回调到启动的Fragment
                    editFragment.setTargetFragment(ContentFragment.this, REQUEST_CODE);
    
                    getFragmentManager().beginTransaction()
                            .hide(ContentFragment.this)
                            .add(R.id.fl_container, editFragment, EditFragment.EDIT_FRAGMENT)
                            .addToBackStack(null)
                            .commit();
                }
            });
    
            differentActivity.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Intent intent = new Intent();
                    intent.putExtra(CONTENT_FRAGMENT, CONTENT_FRAGMENT);
                    getActivity().setResult(RESULT_CODE, intent);
                    getActivity().finish();
                }
            });
            return view;
        }
    
        @Override
        public void onActivityResult(int requestCode, int resultCode, Intent data) {
            super.onActivityResult(requestCode, resultCode, data);
            if (data == null) {
                return;
            }
    
            String name = data.getStringExtra("name");
            content.setText(name);
        }
    }

    NOTE:
    setTargetFragment();相当于一个路标,为返回的数据提供了方向;
    onActivityResult()该方法与Activity中的onActivityResult()作用相同,都是用于接收返回的数据

  • FragmentB代码

    public class EditFragment extends Fragment {
    
    public static final String EDIT_FRAGMENT = EditFragment.class.getSimpleName();
    public static final int RESPONSE_CODE = 0x010;
    
    public static EditFragment newInstance() {
        return new EditFragment();
    }
    
    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_edit, container, false);
        final EditText nameEditText = (EditText) view.findViewById(R.id.et_name);
    
        Button commitButton = (Button) view.findViewById(R.id.btn_commit);
        commitButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                backResult(nameEditText.getText().toString());
            }
        });
        return view;
    }
    
    private void backResult(String name) {
    
        if (getTargetFragment() == null) {
            return;
        }
    
        Intent intent = new Intent();
        intent.putExtra("name", name);
        getTargetFragment().onActivityResult(ContentFragment.REQUEST_CODE, RESPONSE_CODE, intent);
    
        getFragmentManager().popBackStack();
    }
    }

    NOTE:
    在Activity中返回数据,需要调用setResult()方法,数据会自动返回;而Fragment中则需要调用onActivityResult()

不同Activity中,Fragment之间数据回显

该方式其实与Acitivity的数据回显相同,具体看代码

  • ActivityA中的FragmentA启动另外一个ActivityB

    //不同的Activity内Fragment之间的数据回调
    intent = new Intent(getActivity(), SecondActivity.class);
    startActivityForResult(intent, REQUEST_CODE);
  • ActivityB中FragmentB返回数据

    differentActivity.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Intent intent = new Intent();
                    intent.putExtra(CONTENT_FRAGMENT, CONTENT_FRAGMENT);
                    getActivity().setResult(RESULT_CODE, intent);
                    getActivity().finish();
                }
            });
  • FragmentA中接收数据

    @Override
        public void onActivityResult(int requestCode, int resultCode, Intent data) {
            super.onActivityResult(requestCode, resultCode, data);
            if (resultCode == ContentFragment.RESULT_CODE && data != null) {
                Log.i(MAIN_FRAGMENT, data.getStringExtra(ContentFragment.CONTENT_FRAGMENT));
            }
        }

你可能感兴趣的:(Android,Fragment,数据传递,数据回显)