android-fragments Android在两个片段之间共享多个数据

093gszye  于 2022-11-13  发布在  Android
关注(0)|答案(1)|浏览(190)

我想在点击一个按钮后在两个片段之间传递两个变量。我已经读到我可以使用ViewModel类,但我不能真正理解它是如何工作的。我也尝试过使用Bundle,但它不起作用。当我点击按钮时,第二个片段在两个变量上都显示null。
第一个片段文件:

private FragmentWeightBinding binding;
    private EditText edtNumber;
    private Button addBtn;
    private TextView txtDate;
    String sWeight, currentDateAndTime;

    public View onCreateView(@NonNull LayoutInflater inflater,
                             ViewGroup container, Bundle savedInstanceState) {
        WeightViewModel weightViewModel =
                new ViewModelProvider(this).get(WeightViewModel.class);

        binding = FragmentWeightBinding.inflate(inflater, container, false);
        View root = binding.getRoot();
        addBtn = binding.addBtn;
        edtNumber = binding.edtNumber;
        final String[] weight = {""};
        SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy HH:mm");
        currentDateAndTime = sdf.format(new Date());

        addBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                weight[0] = edtNumber.getText().toString();
                sWeight = weight[0];
                Bundle bundle = new Bundle();
                bundle.putString("Weight", sWeight);
                bundle.putString("Date", currentDateAndTime);

                FragmentManager fragmentManager = getActivity().getSupportFragmentManager();
                FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();

                WeightTableFragment weightTableFragment = new WeightTableFragment();
                weightTableFragment.setArguments(bundle);
                fragmentTransaction.commit();
                Toast.makeText(getActivity(),weight[0] + currentDateAndTime, Toast.LENGTH_SHORT).show();
            }
        });

        txtDate= binding.txtDate;
        txtDate.setText(currentDateAndTime);
        return root;
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        binding = null;
    }

}

第二个片段:

private static final String ARG_PARAM1 = "Weight";
    private static final String ARG_PARAM2 = "Date";

    private String weight;
    private String date;

    public WeightTableFragment() {
        // Required empty public constructor
    }

    public static WeightTableFragment newInstance(String sWeight, String currentDateAndTime) {
        WeightTableFragment fragment = new WeightTableFragment();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, sWeight);
        args.putString(ARG_PARAM2, currentDateAndTime);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            weight = getArguments().getString(ARG_PARAM1);
            date = getArguments().getString(ARG_PARAM2);
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View rootView = inflater.inflate(R.layout.fragment_weight_table, container, false);

        TextView text = rootView.findViewById(R.id.weightDate);
        text.setText(String.format(date + ": " + weight));

        return rootView;
    }
5ssjco0h

5ssjco0h1#

如果您希望使用bundle传递(当您创建Empty Fragment时,Android Studio会为您提供基本代码),即:

private static final String ARG_PARAM1 = "param1"; 
 String dataYouWantToSendInFragmentFromActvity;

 public static YourFragmentClassName newInstance(String dataYouWantToSendInFragmentFromActvity) {
        YourFragmentClassName fragment = new YourFragmentClassName ();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, dataYouWantToSendInFragmentFromActvity);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            dataYouWantToSendInFragmentFromActvity = getArguments().getString(ARG_PARAM1);
        }
    }

现在,要从Activity中打开Fragment,而不是创建Fragment的对象,请使用getInstance(Object obj)方法,该方法将把您要发送的数据放在一个包中,并返回fragment对象
下面的代码演示了如何使用它(A点)

FragmentManager fragmentManager = getSupportFragmentManager();
        FragmentTransaction transaction = fragmentManager.beginTransaction();
        transaction.add(R.id.container, YourFragmentClassName .newInstance("YourStringData"));
        transaction.addToBackStack(null);
        transaction.commit();

我在getInstance()方法中使用了String参数,只是为了举例说明,您可以使用任何基元数据类型或Parcelable Object,还可以添加多个对象,并在bundle中添加和在onCreate中赋值
现在,如果您想从一个Fragment向另一个Fragment发送数据,请从FragmentA向Activity回调,Activity将接收数据,并以上述相同的方式将数据发送到另一个FragmentB(在其实现中)。要获取FragmentA中的回调对象,您可以使用FragmentA的覆盖方法onAttach(),如下所示:

Callback callback;
      @Override
        public void onAttach(@NonNull Context context) {
            super.onAttach(context);
            if(context instanceOf CallBack)
              this.callback=context;
        }

现在,在您的情况下,而不是吐司调用回调的方法,可能是callback.openOtherFrag(YOUR_DATA);这将从Activity调用openOtherFrag方法的实现,并发送数据,即YOUR_DATA,如上面(A点)中所做的
快乐编码

相关问题