Fragments disappear when turning

I added fragments using java.

when I open the application in portrait mode, it works.

Scrrenshot

if I rotate the fragment, just disappear.

enter image description here

but if I close the application, then rotate the phone and open the application again, it will work.

enter image description here

I have two different layouts: one for portrait mode and the other for landscape mode, both with the same name, I have a layout for the portrait in the layout folder and a layout for the landscape in the layout-land folder.

It seems to me that I'm forgetting something, sincerely I am new to Android development.

Activity:

  @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        ListFragment frag = new ListFragment();

        setContentView(R.layout.layout_main);

        FragmentManager manager = getFragmentManager();
        FragmentTransaction transaction = manager.beginTransaction();

        transaction.add(R.id.LIST_LAYOUT,frag,"LIST");
        transaction.commit();

    }

Fragment:

public class ListFragment extends Fragment implements AdapterView.OnItemClickListener{


    ListView List;
    Communicator communicator;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        //return super.onCreateView(inflater, container, savedInstanceState);

        return inflater.inflate(R.layout.mlistfragment,container,false);


    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);

        communicator = (Communicator) getActivity();

        List = (ListView) getActivity().findViewById(R.id.listView);

        ArrayAdapter adapter = ArrayAdapter.createFromResource(getActivity(),R.array.StrListButtons,android.R.layout.simple_list_item_1);
        List.setAdapter(adapter);


        List.setOnItemClickListener(this);


    }
+4
source share
4 answers

Fragment , Activity; FragmentManager . , FragmentTransaction if (savedInstanceState == null), Activity. :

if (savedInstanceState == null) {
    getFragmentManager().beginTransaction()
                        .add(R.id.list_layout, new ListFragment(), "LIST")
                        .commit();
}
+12

, onResume()

    FragmentManager manager = getFragmentManager();
    FragmentTransaction transaction = manager.beginTransaction();

    transaction.add(R.id.LIST_LAYOUT,frag,"LIST");
    transaction.commit();

onsaveinstancestate()

-1

setRetainInstance (true); onCreate.

-2

All Articles