[android] How to start Fragment from an Activity

I already want to start my RecipientFragment from my MainActivity and pass data onto the Fragment from my MainActivity. Here is the code that I have implemented. But the fragment does not start.

Bundle bundle = new Bundle();
bundle.putString(ParseConstants.KEY_FILE_TYPE, fileType);
RecipientsFragment keyfile = new RecipientsFragment();
keyfile.setArguments(bundle);
Fragment newFragment = new RecipientsFragment();
FragmentTransaction transaction = getFragmentManager().beginTransaction();
transaction.commit();

I also want to know how to pass intent.setData and get that data in Fragment. Currently I have below code:

RecipientFragment

mMediaUri = getActivity().getIntent().getData();

MainActivity

Intent recipientsIntent = new Intent(this, RecipientsFragment.class);
        recipientsIntent.setData(mMediaUri);

This question is related to android android-fragments

The answer is


In order to accomplish this, it is best to design fragment construct to receive that data and save that data in its bundle arguments.

   class FragmentA extends Fragment{
    public static FragmentA newInstance(YourDataClass data) {

            FragmentA f = new FragmentA();
            Bundle b = new Bundle();
            b.putString("data", data);
            f.setArguments(b);

            return f;
        }
    }

In order to start the fragment from the class, you can do the following

 Fragment newFragment = FragmentA.newInstance(objectofyourclassdata);
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();

// Replace whatever is in the fragment_container view with this fragment,
// and add the transaction to the back stack
transaction.replace(R.id.fragment_container, newFragment);
transaction.addToBackStack(null);

// Commit the transaction
transaction.commit();

However, the data class must be parceable or serializable.

For full information on fragments and best practices on use of fragments, please spend some time on official docs, it is super useful, at least my experience

https://developer.android.com/guide/components/fragments#java


Another ViewGroup:

A fragment is a ViewGroup which can be shown in an Activity. But it needs a Container. The container can be any Layout (FragmeLayout, LinearLayout, etc. It does not matter).

enter image description here

Step 1:

Define Activity Layout:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
   android:layout_width="match_parent"
   android:layout_height="match_parent">
   <FrameLayout
       android:id="@+id/fragmentHolder"
       android:layout_width="match_parent"
       android:layout_height="wrap_content"
    />
</RelativeLayout>

Step 2:

Define Fragment Layout:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:gravity="center"
    android:orientation="vertical">
    <EditText
       android:id="@+id/user"
       android:layout_width="wrap_content"
       android:layout_height="wrap_content"/>
    <EditText
       android:id="@+id/password"
       android:layout_width="wrap_content"
       android:layout_height="wrap_content"
       android:inputType="textPassword"/>
    <Button
       android:id="@+id/login"
       android:layout_width="wrap_content"
       android:layout_height="wrap_content"
       android:text="Login"/>
</LinearLayout>

Step 3:

Create Fragment class

public class LoginFragment extends Fragment {


    private Button login;
    private EditText username, password;

    public static LoginFragment getInstance(String username){
       Bundle bundle = new Bundle();
       bundle.putInt("USERNAME", username);
       LoginFragment fragment = new LoginFragment();
       fragment.setArguments(bundle);
       return fragment;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup parent, Bundle savedInstanceState){
       View view = inflater.inflate(R.layout.login_fragment, parent, false);
       login = view.findViewById(R.id.login);
       username = view.findViewById(R.id.user);
       password = view.findViewById(R.id.password);
       String name = getArguments().getInt("USERNAME");
       username.setText(username);
       return view;
    }

}

Step 4:

Add fragment in Activity

public class ActivityB extends AppCompatActivity{

   private Fragment currentFragment;

   @Override
   protected void onCreate(Bundle savedInstanceState) {

       super.onCreate(savedInstanceState);
       setContentView(R.layout.activity_main);

       currentFragment = LoginFragment.getInstance("Rohit");
       getSupportFragmentManager()
                .beginTransaction()
                .add(R.id.fragmentHolder, currentFragment, "LOGIN_TAG")
                .commit();
   }

}

Demo Project:

This is code is very basic. If you want to learn more advanced topics in Fragment then you can check out these resources:

Woof - Learn the fragment right way
My Android Garage


Firstly, you start Activities and Services with an intent, you start fragments with fragment transactions. Secondly, your transaction isnt doing anything. Change it to something like:

FragmentTransaction transaction = getFragmentManager();
    transaction.beginTransaction()
        .replace(R.layout.container, newFragment) //<---replace a view in your layout (id: container) with the newFragment 
        .commit();

You Can Start Activity and attach RecipientsFragment on it , but you cant start Fragment


Simple way

  1. Create a new java class

    public class ActivityName extends FragmentActivity {
    @Override
     public void onCreate(Bundle savedInstanceState) {
       super.onCreate(savedInstanceState);
        if (savedInstanceState == null){
        getSupportFragmentManager().beginTransaction()
                .add(android.R.id.content, new Fragment_name_which_you_wantto_open()).commit();}
     }
    }
    
  2. in your activity where u want to call fragment

     Intent i = new Intent(Currentactivityname.this,ActivityName.class);
     startActivity(i);
    

Another Method

  1. Place frame layout in your activity where u want to open fragment

      <FrameLayout
            android:id="@+id/frameLayout"
            android:layout_width="match_parent"
            android:layout_height="wrap_content">
        </FrameLayout>
    
  2. Paste this code where u want to open fragment

        Fragment mFragment = null;
            mFragment = new Name_of_fragment_which_you_want_to_open();
            FragmentManager fragmentManager = getSupportFragmentManager();
            fragmentManager.beginTransaction()
                    .replace(R.id.frameLayout, mFragment).commit();