在片段之间发送数据而不创建新片段

时间:2016-01-17 22:02:53

标签: android android-fragments

所以我有一个调用DialogFragment的片段(WifiSetupFragment),而DialogFragment需要将字符串传递回原始片段。我知道这样做你在活动中有一个接口会将数据发送到原始片段,我已经在做了:

FragmentTransaction transaction = getFragmentManager().beginTransaction();
transaction.addToBackStack(null);
transaction.replace(R.id.content_frag, WifiSetupFragment.newInstance(password));
transaction.commit();

所以第一次调用WifiSetupFragment时,我还没有创建一个DialogFragment,因为我没有点击某个项目来打开对话框。我的问题是我应该致电

WifiSetupFragment.newInstance(null)

并对我的片段中的密码字符串进行空检查?因为除非DialogFragment处于打开状态,否则我没有密码,并且它并不总是打开。如果这没有意义,请告诉我,我会尝试更清楚地解释。我想我觉得有一个字符串的参数偶尔会被发送到这个片段,因为数据不会被传入,这对我来说似乎很奇怪。

2 个答案:

答案 0 :(得分:5)

您不需要通过活动在这些片段之间进行通信。你能做什么呢?

  1. WifiSetupFragment.newInstance()不接受任何参数。
  2. WifiSetupFragment实施新界面,让我们称之为OnPasswordSuppliedListener
  3. 创建DialogFragment个实例后,请将其附加到getChildFragmentManager()而不是getFragmentManager()
  4. 现在,在您的DialogFragment子类中,您可以通过调用WifiSetupFragment来引用getParentFragment()
  5. getParentFragment()投射到您的界面并瞧!
  6. 注意:我假设您正在使用支持库中的片段。否则请注意,API 17中引入了嵌套片段功能。

答案 1 :(得分:0)

您的对话框可以定义一个接口,允许将输入密码发送回父片段/活动:

public class TestDialog extends DialogFragment {

    private TextView mPasswordView;
    private OnPasswordDefinedCallback mCallback;

    public static TestDialog newInstance() {
        TestDialog dialog = new TestDialog();
        return dialog;
    }

    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState) {
        // inflate layout for your dialog (it must include edit text for password)
        LayoutInflater inflater = getActivity().getLayoutInflater();
        View layout = inflater.inflate(R.layout.dialog_test, null);
        // getting ui elements from layout
        mPasswordView = (TextView) layout.findViewById(R.id.txt_password);
        // building dialog
        AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
        builder.setView(layout);
        builder.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                try {
                    mCallback = (OnPasswordDefinedCallback) getTargetFragment();
                } catch (ClassCastException e) {
                    throw new ClassCastException("must implement OnPasswordDefinedCallback");
                }
                if (mCallback != null) {
                    // send password back to parent
                    mCallback.doPasswordDefined(mPasswordView.getText().toString());
                }
                dismiss();
            }
        });
        return builder.create();
    }


    public interface OnPasswordDefinedCallback {

        void doPasswordDefined(String password);

    }

}

然后在WifiSetupFragment中,您可以按照以下步骤开启PasswordDialog

TestDialog dialog = TestDialog.newInstance();
dialog.setTargetFragment(WifiSetupFragment.this, 1);
dialog.show(getChildFragmentManager(), null); 

WifiSetupFragment当然必须实现接口OnPasswordDefinedCallback