简体   繁体   中英

Passing argument from fragment to activity using SafeArgs

Using navigation graph, when i navigate from fragment to activity and also passing argument using safeargs, in activity, I cannot get argument. How can I get argument passing from fragment???

In fragment, I can get argument by getArgument() function, but not in activity.

In fragment I switch to another activity by:

findNavController().navigate(AFragmentDirections.actionAFragmentToBActivity(1)

and in B activity get argument in onCreate by:

val args = BActivityArgs.fromBundle(savedInstanceState!!)

but my app crash immediately.

The accepted answer is not an answer to your question. As you point out: you cannot use getArguments() in your Activity , you can only do that in a fragment. However, in an activity you can get the data like this (java syntax):

String aField = BActivityArgs.fromBundle(getIntent().getExtras()).getAField()

So, just replace getArguments() with getIntent().getExtras() if you have an Activity on the receiving end.

Check it out the Android Doc:-

https://developer.android.com/guide/navigation/navigation-pass-data#java

Send Data

@Override
public void onClick(View view) {
EditText amountTv = (EditText) getView().findViewById(R.id.editTextAmount);
int amount = Integer.parseInt(amountTv.getText().toString());
ConfirmationAction action =
       SpecifyAmountFragmentDirections.confirmationAction()
action.setAmount(amount)
Navigation.findNavController(view).navigate(action);
}

Get Data:-

@Override
public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
TextView tv = view.findViewById(R.id.textViewAmount);
int amount = ConfirmationFragmentArgs.fromBundle(getArguments()).getAmount();
tv.setText(amount + "")
}
BActivityArgs.fromBundle(getIntent().getExtras()).getAField();

Work perfectly

  • As stated in the official documentation HERE :

The Navigation component is designed for apps that have one main activity with multiple fragment destinations. The main activity is associated with a navigation graph and contains a NavHostFragment that is responsible for swapping destinations as needed. In an app with multiple activity destinations, each activity has its own navigation graph

  • A solution might be: rethink if the activity could be converted to a Fragment and then the newly created Fragment could be handled by the same Navigation Component. Thus allowing you to use the normal SafeArgs syntax to pass and retrieve data.

  • If you are still having problems with the SafeArgs plugin, I would highly recommend this medium article by the official Android team, HERE

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM