Federick Jons Federick Jons - 4 months ago 40
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() {
@Override
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);
ft.commit();
}

}
});


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

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

@Override
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_height="match_parent">

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="HOLAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"
android:id="@+id/textView35"
android:layout_gravity="center_horizontal" />
</LinearLayout>


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

Answer

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.