I’ve added the fragments using java.
when I open the app in portrait mode it works.
if I rotate the fragment just disappear.
but if I close the app, then rotate the phone, and then open the app again, it works.
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);
}
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();
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With