简体   繁体   中英

How to pass intent from activity to fragment in Android

Hello am new to Android how to give intent from Activity to fragment? I know from Fragment to Activity like this

Intent intent=new Intent(getActivity(),nextActivity.class)
StartActivity(intent);

But I want from Activity to Fragment.

You cannot pass the intent to the fragment, what you can do is get the data you have in the intent and pass it to the fragment. The recommended way to do that is to use the newInstance pattern. So in the fragment you'll have this:

    public static MyFragment newInstance(@NonNull final String someId) {
        final MyFragment fragment = new ProfileFragment();
        final Bundle args = new Bundle();
        args.putString(Const.KEY_SOME_ID, someId);

        fragment.setArguments(args);

        return fragment;
    }

To create the fragment of course you'll call that method.

String id = getIntent().getStringExtra(Const.KEY_ID);
MyFragment fragment = MyFragment.newInstance(id);

and to access it inside the fragment you need to get from arguments:

    Bundle args = getArguments();
    if (args != null) {
        myId = args.getString(Const.KEY_SOME_ID, "");
    }

Currently I am working on Fragment.
use this code.

Fragment fragment =  new YourFragmentName();
if (fragment != null) {
            FragmentManager fragmentManager = getFragmentManager();
            fragmentManager.beginTransaction().replace(R.id.content_frame, fragment).commit();
        }

Where content_frame is

<FrameLayout
        android:id="@+id/content_frame"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

in main layout

In Activity you set data in intent

Bundle bundle = new Bundle();
bundle.putString("dataKey", "Value");
YourFragmentClass fragmentObject = new YourFragmentClass();
fragmentObject .setArguments(bundle);
if(fragmentObject!=null){
        FragmentManager fm = getFragmentManager();
        fm.beginTransaction().add(R.id.container, fragmentObject).commit();
    }

In Fragment's onCreateView method you can get the data

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
    Bundle savedInstanceState) {

String activityData= getArguments().getString("dataKey");  

return inflater.inflate(R.layout.fragment, container, false);

}

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