如何更改片段中分离/附加的参数?

时间:2019-01-15 13:25:42

标签: android android-fragments arguments

我有一个从活动中调用的片段,该片段加载后会生成一些图表。现在,我必须更新那些图表,但是用于更新那些图表的数据来自该片段的参数。

public static BaseFragment newInstance(WholeReportsData wholeReportsDataFB, WholeReportsData wholeReportsDataTeam) {
    MainReportFragment fragment = new MainReportFragment();
    Bundle args = new Bundle();
    args.putParcelable(ARG_WHOLEREPORTSINFO_FB, wholeReportsDataFB);
    args.putParcelable(ARG_WHOLEREPORTSINFO_TEAM, wholeReportsDataTeam);
    fragment.setArguments(args);
    return fragment;
}

@Override
public void onCreate(@android.support.annotation.Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    if (getArguments() != null) {
        mWholeReportsDataFB = getArguments().getParcelable(ARG_WHOLEREPORTSINFO_FB);
        mWholeReportsDataTeam = getArguments().getParcelable(ARG_WHOLEREPORTSINFO_TEAM);
    } else {
        mWholeReportsDataFB = new WholeReportsData();
        mWholeReportsDataTeam = new WholeReportsData();
    }
}

我正在像下面的代码一样更新片段,但是我不知道如何更新参数。

private void reloadFragment(){

        mReportsPresenter = ((HomeActivity)getActivity()).getReportPresenter();

        mWholeReportsDataFB = new WholeReportsData(null, "", true);
        mWholeReportsDataTeam = new WholeReportsData();
        mReportsPresenter.requestReportsInfo(new ReportsRequestParams(getActivity(), ReportsRequestParams.TYPE_FAMILYBANKER));
        if (SessionUserResult.getInstance().getFamilyBanker().isEsSupervisor()) {
            mReportsPresenter.requestReportsInfo(new ReportsRequestParams(getActivity(), ReportsRequestParams.TYPE_TEAM));
            mWholeReportsDataTeam.setLoadingService(true);
        }



        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            getActivity().getSupportFragmentManager().beginTransaction().detach(this).commitNow();
            getActivity().getSupportFragmentManager().beginTransaction().attach(this).commitNow();
        } else {
            getActivity().getSupportFragmentManager().beginTransaction().detach(this).attach(this).commit();
        }

    }

谢谢

1 个答案:

答案 0 :(得分:0)

您可以在活动和片段之间使用共享视图模型并更新图表, 检查此How to communicate between fragments and activity using ViewModel

或者您可以检查参数是否不为null,然后更新它们,否则设置新的参数

Bundle bundle = new Bundle();
    bundle.putLong(Constants.EXTRA_DO_ID, doId);
    bundle.putInt(Constants.EXTRA_DO_OPTIONS_DIALOG_MODE, MODE_GET_INSPIRE_BY_DO);
    if (fragment.getArguments() != null) {
        fragment.getArguments().putAll(bundle);
    } else
        fragment.setArguments(bundle);