Federick Jons Federick Jons - 3 months ago 23
Android Question

Open fragment from activity?

I wanna open fragment from my activity. The problem is that the fragment never appears.
This is the part of my activity:

btn_opciones.setOnValueChangedListener(new ToggleButton.OnValueChangedListener() {
public void onValueChanged(int position) {
if(position == 1){
OrdenarComplejosFragment ordenarComplejosFragment = new OrdenarComplejosFragment();
FragmentManager manager = getSupportFragmentManager();
FragmentTransaction ft = manager.beginTransaction();

ft.setCustomAnimations(R.anim.fade_in, R.anim.fade_out);
ft.add(ordenarComplejosFragment, null);


And this is my fragment that I wanna open and show:

public class OrdenarComplejosFragment extends Fragment {
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_ordenar_complejos, container, false);

public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
//do your stuff for your fragment here

The xml of the fragment above:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"

android:layout_gravity="center_horizontal" />

I don't know why the fragment never show. The button works fine.


Try using a different "add" method. Using the one which takes in a view id indicates where the fragment should show up within the existing Activity's layout.

ft.add(R.id.fragment_frame, ordenarComplejosFragment);

Fragments are always housed within an Activity. If your activity doesn't provide a container/location for the fragment to show up, you'll need to re-think the layout or consider opening this new view with a separate Activity.