tcmike
tcmike

Reputation: 57

Display a different fragment on an activity?

Question: How do I make an activity change fragments when I press a button on a displayed fragment?

I have an activity (HomeActivity) and inside is the following code:

public class HomeActivity extends AppCompatActivity
    implements WelcomeFragment.OnFragmentInteractionListener{

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_home);

    WelcomeFragment welcomeFragment = new WelcomeFragment();
    Bundle myBundle = getIntent().getExtras();
    welcomeFragment.signedUsername = myBundle.getString("username");

    this.pushFragment(welcomeFragment, false);
}

void pushFragment(Fragment newFragment, boolean addToStack) {
    // Create a FragmentTransaction from FragmentManager via activity
    FragmentManager manager = getSupportFragmentManager();
    FragmentTransaction transaction = manager.beginTransaction();
    // Replace whatever is in the fragment_container view with this fragment
    transaction.replace(R.id.loginFragmentContainer, newFragment);
    if (addToStack) {
        // Add the transaction to the back stack
        transaction.addToBackStack(null);
    }
    //Commit the transaction
    transaction.commit();
}

@Override
public void onFragmentInteraction(Uri uri) {

}

}

On the welcome fragment, I have 4 buttons. I want each button to take me to a different fragment for data calculations. Any tips on how to achieve this would be greatly appreciated.

WelcomeFragment code:

public class WelcomeFragment extends Fragment  {
// TODO: Rename parameter arguments, choose names that match
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";

// TODO: Rename and change types of parameters
private String mParam1;
private String mParam2;

String signedUsername;
TextView textWelcome;

private OnFragmentInteractionListener mListener;

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

/**
 * Use this factory method to create a new instance of
 * this fragment using the provided parameters.
 *
 * @param param1 Parameter 1.
 * @param param2 Parameter 2.
 * @return A new instance of fragment WelcomeFragment.
 */
// TODO: Rename and change types and number of parameters
public static WelcomeFragment newInstance(String param1, String param2) {
    WelcomeFragment fragment = new WelcomeFragment();
    Bundle args = new Bundle();
    args.putString(ARG_PARAM1, param1);
    args.putString(ARG_PARAM2, param2);
    fragment.setArguments(args);
    return fragment;
}

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

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

    textWelcome = view.findViewById(R.id.textWelcomeMessage);
    textWelcome.setText("Welcome " + signedUsername + "!");

    return  view;
}

// TODO: Rename method, update argument and hook method into UI event
public void onButtonPressed(Uri uri) {
    if (mListener != null) {
        mListener.onFragmentInteraction(uri);
    }
}

@Override
public void onAttach(Context context) {
    super.onAttach(context);
    if (context instanceof OnFragmentInteractionListener) {
        mListener = (OnFragmentInteractionListener) context;
    } else {
        throw new RuntimeException(context.toString()
                + " must implement OnFragmentInteractionListener");
    }
}

@Override
public void onDetach() {
    super.onDetach();
    mListener = null;
}

public interface OnFragmentInteractionListener {
    // TODO: Update argument type and name
    void onFragmentInteraction(Uri uri);
}

}

Upvotes: 0

Views: 258

Answers (2)

skryshtafovych
skryshtafovych

Reputation: 582

Create Another Activity like ParentActivityForFragment than call From Home Activity with an Bundle/Intent that includes data you need to inflate like screen and any other data needed . Now that you have activity handling you Fragment inflation you can now control what Parent does with Fragments or Activity.

Upvotes: 0

Orbit
Orbit

Reputation: 2385

Bad UX aside, the answer to this question is a matter of simply communicating with your Activity.

There's a few ways to do this, such as using an event bus, RxJava, or a traditional callback.

A callback would look something like the following:

Chuck an interface into your Fragment:

interface ChangeFragmentCallback {
    void changeFragment(int which);
}

Let your Fragment accept the callback using either the constructor or a setter method. We'll use the constructor:

Fragment(ChangeFragmentCallback callback) {
    this.callback = callback;
}

In your Activity, whenever you instantiate this fragment, pass in the callback:

new Fragment(new Fragment.ChangeFragmentCallback() {
    @Override                                                           
    public void changeFragment(int which) {
        // Put code to change the fragment here.                                                                                      
    }                                                                   
});

Then whenever you want to tell your Activity that the Fragment should change (such as when some button is clicked) just call callback.changeFragment().

You could also just use a ViewPager which holds all the Fragments and then just tell the adapter for the ViewPager to swap pages.

Finally, all Fragments have a getActivity() method. You could call this method and cast the return value to your Activity, and then call whatever methods you like:

((HomeActivity)getActivity()).pushFragment();

Upvotes: 1

Related Questions