【问题标题】:onAttach() never called in DialogFragmentonAttach() 从未在 DialogFragment 中调用
【发布时间】:2012-12-28 13:30:32
【问题描述】:

我尝试从DialogFragment 实现回调。 有一个很好的例子,但他们不会从Fragment 打开这个DialogFragmenthttp://developer.android.com/guide/topics/ui/dialogs.html#PassingEvents

这是我的代码:

public class EditDateDialogFragment extends DialogFragment {
    // Use this instance of the interface to deliver action events
    EditDateDialogListener mListener;

    /* The activity that creates an instance of this dialog fragment must
     * implement this interface in order to receive event callbacks.
     * Each method passes the DialogFragment in case the host needs to query it. */
    public interface EditDateDialogListener {
        public void onDialogPositiveClick(DialogFragment dialog);
        public void onDialogNegativeClick(DialogFragment dialog);
    }


    public static EditDateDialogFragment newInstance( int currentCategoryId ) {
        EditDateDialogFragment p = new EditDateDialogFragment();
        Bundle args = new Bundle();
        args.putInt("currentRecordId", currentCategoryId);
        p.setArguments(args);
        return p;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        mCurrentRecordId = getArguments().getInt("currentRecordId");
        super.onCreate(savedInstanceState);
    }

    public void onAttach(SherlockActivity activity) {

        super.onAttach(activity);

        try {
            // Instantiate the EditDateDialogListener so we can send events to the host
            mListener = (EditDateDialogListener) activity;
        } catch (ClassCastException e) {
            // The activity doesn't implement the interface, throw exception
            throw new ClassCastException(activity.toString() + " must implement EditDateDialogListener");
        }

    }

        @Override
    public Dialog onCreateDialog(Bundle savedInstanceState) {
        LayoutInflater inflater = LayoutInflater.from(getActivity());
        final View v = inflater.inflate(R.layout.fragment_dialog_edit_date, null);

        return new AlertDialog.Builder(getActivity()).setTitle("Set Date...").setView(v).setCancelable(true).setPositiveButton("Confirm", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                Log.d("", "Dialog confirmed");

                mListener.onDialogPositiveClick(EditDateDialogFragment.this);

            }
        }).setNegativeButton("Abort", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                Log.d("", "Dialog abort");
                dialog.cancel();
            }
        }).create();
    }
}

在 RecordDetailFragment.java 中,我实现了接口并以这种方式创建了 EditDateDialogFragment 的新实例(只是重要部分):

public class RecordDetailFragment extends SherlockFragment implements EditDateDialogFragment.EditDateDialogListener {
...
 DialogFragment editDateFragment = EditDateDialogFragment.newInstance( recordId );
             editDateFragment.show(getActivity().getSupportFragmentManager(), "EditDateDialogFrame");
@Override
    public void onDialogPositiveClick(DialogFragment dialog) {
        LOGD(TAG, "Overriden Dialog confirmed");
        //((EditDateDialogFragment) dialog).mDatePicker;

    }

    @Override
    public void onDialogNegativeClick(DialogFragment dialog) {
        // TODO Auto-generated method stub

    }
...
}

现在 EditDateDialogFragment 中的公共 void onAttach(SherlockActivity activity) 永远不会被调用,因为我从 Fragment 而不是 Activity 创建了 DialogFragment? 如何解决这个问题?

更新: 在 RecordDetailFragment 中,我将其插入 onCreate()

if (savedInstanceState != null) {
    EditDateDialogFragment dpf = (EditDateDialogFragment) getActivity().getSupportFragmentManager().findFragmentByTag("EditDateDialogFragment");
    if (dpf != null) {
        dpf.setListener((EditDateDialogListener) this);
    }
}

我将 DialogFragment 的实例化更改为

 EditDateDialogFragment editDateFragment = EditDateDialogFragment.newInstance( recordId );
             editDateFragment.setListener((EditDateDialogListener) this);
             editDateFragment.show(getActivity().getSupportFragmentManager(), "EditDateDialogFragment");

注意 EditDateDialogFragment 而不是 DialogFragment。 我不确定如何更新对话框中的引用。

【问题讨论】:

    标签: android callback android-fragments android-dialog android-dialogfragment


    【解决方案1】:

    刚跳进同样的问题,解决方法很简单。而不是覆盖

    public void onAttach(Context context) {}
    

    覆盖这个:

    public void onAttach(Activity activity) {}
    

    DialogFragment 现在一切正常。

    【讨论】:

      【解决方案2】:

      如何解决这个问题?

      我猜您希望RecordDetailFragment 实例的行为与DialogFragmentEditDateDialogListener 相同。如果是,那么您需要将其显式设置(并更新)为侦听器:

      DialogFragment editDateFragment = EditDateDialogFragment.newInstance( recordId );
      editDataFragment.setListener(RecordDetailFragment.this);
      editDateFragment.show(getActivity().getSupportFragmentManager(), "EditDateDialogFrame");
      

      其中setListener()EditDialogFragment 中的一个方法,如下所示:

      public void setListener(EditDateDialogListener listener) {
           mListener = listener;
      }
      

      例如,当用户旋转手机时,将重新创建 Activity 及其片段,您需要重新设置侦听器以指向新创建的 RecordDetailFragment 实例(您可能希望使用 WeakReferencemListener)。您可以找到类似的东西in this answer(您将在onCreate 中寻找两个片段)。

      编辑:在ActivityonCreate方法中:

      if (savedInstanceState != null) {
          RecordDetailFragment df = (RecordDetailFragment) getSupportFragmentManager().findFragmentByTag("rdf"); // "rdf" is the tag used when you add the RecordDetailFragment to the activity
          EditDateDialogFragment s = (EditDateDialogFragment) getSupportFragmentManager().findFragmentByTag("tag"); // "tag" is the string set as the tag for the dialog when you show it
          if (s != null) {
                         // the dialog exists so update its listener
              s.setListener(df);
          }
      }
      

      【讨论】:

      • 我没有让监听器更新工作。我必须在您的评论中更新听众参考的描述对我来说有点不精确。
      • @No3x 你能分享一些关于你如何更新监听器的信息/代码吗?
      • 我很困惑..在哪个活动中?我想在 Fragment 和 DialogFragment 之间进行通信。
      • @No3x 你在哪里使用这两个片段?他们不是放在FragmentActivity/Activity吗?
      【解决方案3】:

      onCreateDialog 中的某处将 mListener 转换为 getActivity():

      try {
          mListener = (EditDateDialogListener) getActivity();
      } catch (Exception e) {
          throw new ClassCastException(getActivity().toString()
                  + " must implement EditDateDialogListener");
      }
      

      【讨论】:

        【解决方案4】:

        更“现代”的方法是使用新的Fragment Result API

        在 Fragment A(父)onCreate 上添加结果侦听器:

        override fun onCreate(savedInstanceState: Bundle?) {
            super.onCreate(savedInstanceState)
        
            childFragmentManager.setFragmentResultListener("requestKey", this) { key, bundle ->
                val result = bundle.getString("bundleKey")
            }
        
        }
        

        根据需要,在子片段 B 上设置结果(例如,在按钮单击侦听器上):

        button.setOnClickListener {
            val result = "resultSample"
        
            setFragmentResult("requestKey", bundleOf("bundleKey" to result))
        }
        

        有关文档的更多信息:https://developer.android.com/guide/fragments/communicate#kotlin

        【讨论】:

          猜你喜欢
          • 2018-01-30
          • 2015-12-12
          • 1970-01-01
          • 2020-09-05
          • 1970-01-01
          • 1970-01-01
          • 2014-10-11
          • 2013-10-15
          • 1970-01-01
          相关资源
          最近更新 更多