I have a performance issue when using MapFragment
together with the action bar menu.
The bug emerges when three conditions are met
MapFragment
instantiated.Opening the options menu again and dismissing it again fixes the issue.
The behavior does not arise when
onCreate()
popBackStack
from the options menuMinimal working example (requires access to Google Maps API):
import android.app.Activity;
import android.app.Fragment;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import com.google.android.gms.maps.MapFragment;
public class MapFragmentBugActivity extends Activity {
Fragment mMapFragment;
String MAP = "Map";
String BLANK = "Blank";
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_fragment_bug);
mMapFragment = new MapFragment();
getFragmentManager().beginTransaction()
.replace(R.id.main, mMapFragment)
.commit();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
menu.add(MAP);
menu.add(BLANK);
return super.onCreateOptionsMenu(menu);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
Fragment fragment;
if (item.getTitle().equals(MAP)) {
fragment = mMapFragment;
} else {
fragment = new Fragment();
}
getFragmentManager()
.beginTransaction()
.replace(R.id.main, fragment)
.addToBackStack(null)
.commit();
return true;
}
}
Activity layout, nothing special
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/main"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:clickable="true" />
The fragment transaction is performed before the options menu is closed, this causes the weird behavior.
Instead of directly performing the fragment transaction, post it on the Handler
. Once the options menu is closed, then the fragment transaction will be performed.
Try this :
@Override
public boolean onOptionsItemSelected(MenuItem item) {
final Fragment fragment;
if (item.getTitle().equals(MAP)) {
fragment = mMapFragment;
} else {
fragment = new Fragment();
}
Handler handler = new Handler();
handler.post(new Runnable() {
@Override
public void run() {
getFragmentManager()
.beginTransaction()
.replace(R.id.main, fragment)
.addToBackStack(null)
.commit();
}
});
return true;
}
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