Question

I got a problem in changing mapfragments to other fragments. (Listfragment or text) When I use fragmenttransaction to a fragment with only text. The map is still there, and new fragment is over the map. I cannot remove the map.

I searched it, but did not find good approach. Can someone provide some ideas?

This is the main activity.that extends Activity enter code here

protected void onCreate(Bundle savedInstanceState) {
      if (android.os.Build.VERSION.SDK_INT > 9) {
          StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
          StrictMode.setThreadPolicy(policy);
        }
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
FragmentManager myfm = getFragmentManager();
FragmentTransaction ft = myfm.beginTransaction();
mymap = new StartFragment();
    ft.add(R.id.map, mymap);
    ft.commit();

This is the fragment in activity_main;

    <fragment
    android:id="@+id/map"
    android:name="com.google.android.gms.maps.MapFragment"
    android:layout_below="@+id/Deerfield"
    android:layout_width="match_parent"
    android:layout_height="match_parent" />

This is the start_fragment class

public class StartFragment extends Fragment  {
@Override
 public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle     savedInstanceState) { 
      View view = inflater.inflate(R.layout.map_layout,null);
    return view;
 } 
 }

Then the map_layout

<?xml version="1.0" encoding="utf-8"?>
<fragment xmlns:android="http://schemas.android.com/apk/res/android"
 android:id="@+id/map"
 android:layout_width="fill_parent"
 android:layout_height="fill_parent"
 class="com.google.android.gms.maps.MapFragment"/>

Thank you!

Was it helpful?

Solution

There are a couple of problems in your code.

First of all, you cannot replace a fragment added in xml. You can only add this fragment inside code and then use FragmentTransaction.replace to switch to other fragment.

Another thing is you cannot add a fragment inside fragment in xml. Read this http://developer.android.com/about/versions/android-4.2.html#NestedFragments for more details.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top