Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fragments disappear when rotated

I’ve added the fragments using java.

when I open the app in portrait mode it works.

ScrrenShot

if I rotate the fragment just disappear.

enter image description here

but if I close the app, then rotate the phone, and then open the app again, it works.

enter image description here

i have two different layouts one for portrait mode other for landscape mode, both with the same name, i have the layout for portrait in the "layout" folder, and the layout for landscape on "layout-land" folder.

it seems like i am forgetting something, sincerely i am new on 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);


    }
like image 829
user1519426 Avatar asked Jan 09 '14 05:01

user1519426


1 Answers

You actually don't need to add the Fragment every time the Activity is created; the FragmentManager maintains them automatically. You should wrap the code which does the FragmentTransaction in an if (savedInstanceState == null) check, so that it is only executed the first time the Activity is created. For example:

if (savedInstanceState == null) {
    getFragmentManager().beginTransaction()
                        .add(R.id.list_layout, new ListFragment(), "LIST")
                        .commit();
}
like image 136
Kevin Coppock Avatar answered Oct 31 '22 20:10

Kevin Coppock