Zidane
Zidane

Reputation: 1904

How to move from an activity to a fragment in Android?

May you assist by telling me the best way to moves from an activity to a fragment. This is what I have so far but it doesnt seem to work. This is how I am calling the function(getCategory)

private void selectItem( int group, int usage)
   {
      if (!shown) return;
      classificationGroup = group;

      ((DashboardActivity)getActivity()).getCallCategory(classificationGroup);
   }

And in the activity I am trying to move to a fragment

public Fragment getCallCategory(int position) {


      return new CallLogsFragment();
   }

Upvotes: 1

Views: 4512

Answers (1)

Tomislav Turcic
Tomislav Turcic

Reputation: 889

The standard pattern for creating fragments looks like this:

Inside your fragment class (make sure to import the android.support.v4.app.Fragment):

public class MyFragment extends Fragment {

    public static final String TAG = "MyFragment";

    private int position;

    // You can add other parameters here
    public static MyFragment newInstance(int position) {
        Bundle args = new Bundle();
        // Pass all the parameters to your bundle
        args.putInt("pos", position);
        MyFragment fragment = new MyFragment();
        fragment.setArguments(args);
        return fragment;
    }


    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        this.position = getArguments().getInt("pos");
    }
}

Inside your activity:

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        // Add your parameters
        MyFragment fragment = MyFragment.newInstance(10);
        // R.id.container - the id of a view that will hold your fragment; usually a FrameLayout
        getSupportFragmentManager().beginTransaction()
            .add(R.id.container, fragment, MyFragment.TAG)
            .commit();
    }
}

When you want to access public methods of your fragment instance, use FragmentManager#findFragmentByTag(String tag) to find your instance of fragment:

    MyFragment fragment = (MyFragment) getSupportFragmentManager().findFragmentByTag(MyFragment.TAG);
    if(fragment != null){
        // Do something with fragment
    }

For a more detailed explanation, I suggest you read the official docs on fragments: https://developer.android.com/guide/components/fragments.html

Upvotes: 1

Related Questions