片段,DialogFragment问题

时间:2017-04-23 18:28:10

标签: android android-fragments android-dialogfragment fragment-backstack

我从FragmentA调用对话框片段并将一些值返回到fragmentA。现在问题是每当我从同一个fragmentA转到另一个fragmentB并返回它我的对话框片段值被清除

当我点击顾问医生textview时,会打开一个对话框(图2)。在选择项目(图2)时,将值返回到FragmentA。图3是片段B,其打开相同的活动。但是,当我点击图3和popBackStack上的交叉按钮时,我的咨询医生的价值清晰显示在图4中。

enter image description here

enter image description here

enter image description here

enter image description here

Pic 4 is an ISSUE

DialogFragment

 @Override
  public void onStart() {
    super.onStart();
    getDialog().getWindow().setLayout(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
    getDialog().getWindow().setGravity(Gravity.CENTER);
    getDialog().setCancelable(false);
    getDialog().setCanceledOnTouchOutside(false);
    getDialog().closeOptionsMenu();

  }

  @Override public void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setRetainInstance(true);
  }

  @Nullable @Override
  public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container,
      @Nullable Bundle savedInstanceState) {
    getDialog().requestWindowFeature(Window.FEATURE_NO_TITLE);

    View rootView = inflater.inflate(R.layout.consultant_doc_dialog, container, false);

    recyclerView = (RecyclerView)rootView.findViewById(R.id.recycler_view);
    recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
    recyclerView.setHasFixedSize(true);
    adapter = new ConsultantDoctAdapter(getContext(),this);
    adapter.getDocList().addAll(new ArrayList<DoctorList>());
    recyclerView.setAdapter(adapter);
    adapter.getDocList().clear();
    adapter.getDocList().addAll(list);
    adapter.notifyDataSetChanged();


    close = (ImageButton)rootView.findViewById(R.id.bt_close);
    close.setOnClickListener(new View.OnClickListener() {
      @Override public void onClick(View view) {
        getDialog().dismiss();
      }
    });
    //cityEditText.setOnQueryTextListener(onQueryTextListener);

    return rootView;
  }

片段

@Nullable @Override
  public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container,
      @Nullable Bundle savedInstanceState) {
    View view = inflater.inflate(R.layout.layout_create_leads, container, false);
    ButterKnife.bind(this, view);
    setRetainInstance(true);

      init();
      setPicker();
      setSpinnerListener();
      btCheckCalendar.setOnClickListener(this);
      etCityId.setOnClickListener(this);
      etConsultingDocId.setOnClickListener(this);
      btSubmit.setOnClickListener(this);
      tvClientReferral.setOnClickListener(this);
      etSalesPerson.setText(sharedPref.getString(AppConstants.PREFERENCE_USER_NAME, ""));
      etZone.setText(sharedPref.getString(AppConstants.USER_ZONE, ""));
      etAreaCode.setText(sharedPref.getString(AppConstants.USER_AREA_CODE, ""));
      setSpinner();
      getConsultantDoctorList();
    return view;
  }

片段B callBack:

getActivity().getSupportFragmentManager()
    .beginTransaction()
    .replace(R.id.content_main, new MyCalendarFragment())
    .addToBackStack("calendarFragment")
    .commit();

DialogCallack:

ConsultantDocDialogFragment consultantDocDialog = new ConsultantDocDialogFragment();
        consultantDocDialog.setParameter(getContext(), this, doclist);
        consultantDocDialog.show(getActivity().getSupportFragmentManager(),
            ConsultantDocDialogFragment.class.getSimpleName());
        break;

请帮助我,以便我能够保存从对话框片段中获取的值的状态。

4 个答案:

答案 0 :(得分:1)

从DialogFragment返回值的一种简单方法是使用setTargetFragment来调用fragmentB创建,然后将数据返回到getTargetFragment(如果不为null)。在fragmentA中,您可以通过onActivityResult接收数据。

另一种方法是使用SharedPreferences。您可以使用onResumeonHiddenChanged获得新值。

答案 1 :(得分:1)

请找到以下可能对您有帮助的代码 -

这是片段代码,您可以从Dialog Fragment获取CallBack -

HomeFragment.java

public class HomeFragment extends Fragment implements AlertDFragment.Callback {
    private static final int DIALOG_FRAGMENT = 100;
    Button alertdfragbutton;
    private View rootView;

    public HomeFragment() {
    }

    public static HomeFragment newInstance() {
        return new HomeFragment();
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        rootView = inflater.inflate(R.layout.fragment_home, container, false);
        initUI(rootView);
        return rootView;
    }

    private void initUI(View rootView) {
        alertdfragbutton.setOnClickListener(new View.OnClickListener() {
            public void onClick(View arg0) {
                AlertDFragment alertdFragment = new AlertDFragment();
                alertdFragment.setTargetFragment(HomeFragment.this, DIALOG_FRAGMENT);
                // Show Alert DialogFragment
                alertdFragment.show(getChildFragmentManager(), "Alert Dialog Fragment");
            }
        });
    }

    @Override
    public void accept() {
        Log.e("Home  ", "OK");
    }

    @Override
    public void decline() {

    }

    @Override
    public void cancel() {
        Log.e("Home  ", "CANCEL");
    }
}

这是Dialog Fragment,我们用方法声明CallBack -

public class AlertDFragment extends DialogFragment {
    Callback callback;

    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState) {
        callback = (Callback) getTargetFragment();
        return new AlertDialog.Builder(getActivity())
                // Set Dialog Icon
                .setIcon(R.drawable.androidhappy)
                // Set Dialog Title
                .setTitle("Alert DialogFragment")
                // Set Dialog Message
                .setMessage("Alert DialogFragment Tutorial")

                // Positive button
                .setPositiveButton("OK", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {
                        callback.accept();
                        // Do something else
                        //getTargetFragment().onActivityResult(getTargetRequestCode(), Activity.RESULT_OK, getActivity().getIntent());
                    }
                })

                // Negative Button
                .setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {
                        callback.cancel();
                        // Do something else
                        // getTargetFragment().onActivityResult(getTargetRequestCode(), Activity.RESULT_CANCELED, getActivity().getIntent());
                    }
                }).create();
    }

    public static interface Callback {
        public void accept();

        public void decline();

        public void cancel();
    }
}

答案 2 :(得分:0)

而不是使用&#34; Fragment Transition&#34;为什么不直接弹出自定义视图 只需创建

的全局参考
Dialogue dialogue
View popupView

并点击任何文本视图按钮等。 你可以调用类似

的方法
void popup(){
    popupView = LayoutInflater.from(getActivity()).inflate(R.layout.your_calenderlayout, null);
    //suppose you have TextView cal_textview in popUp view i.e, your_calenderlayout
    cal_textview    = (TextView ) popupView.findViewById(R.id.cal_textview);
    dialog          = new Dialog(getContext());
    dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
    dialog.setCanceledOnTouchOutside(true);
    dialog.setContentView(popupView); //and just add your popUpview
    // For setting backgroung
    /*dialog.getWindow().setBackgroundDrawableResource(android.R.color.Transparent);
      */ 
    //For setting the width or height of popup     
    /*WindowManager.LayoutParams lp = new WindowManager.LayoutParams();

    lp.copyFrom(dialog.getWindow().getAttributes());

    lp.width = WindowManager.LayoutParams.WRAP_CONTENT;

    lp.height = WindowManager.LayoutParams.WRAP_CONTENT;

    lp.gravity = Gravity.CENTER;
    dialog.getWindow().setAttributes(lp);*/
    dialog.show();
    }

并且在关闭popUp或单击popupView中的视图时,您可以直接在片段内设置变量或成员的值

希望这会有所帮助

答案 3 :(得分:0)

您可以使用共享首选项或sqlite来获取您的值,如果您认为减少使用它来将您的临时数据保存在share prefs或sqlite中那么Singleton模型是一个不错的选择..我相信我们应该遵循KISS 设计原则:P