2017-10-04 279 views
1

我是Xamarin的新手。我創建了一個使用DrawerLayout(Android)的應用程序。但我的問題是,每次我在菜單(DrawerLayout菜單)中選擇一個項目時,內存都會增加,這會導致應用程序變得緩慢並被粉碎。我試圖使用Xamarin分析器來分析內存泄漏 - 它懷疑稱爲String.FastAllocationString的東西,但它並沒有真正顯示導致String.FastAllocationString問題的行(代碼)。請幫忙 ?這裏是我的代碼:Xamarin內存泄漏

MainActivity

DrawerLayout drawerLayout; 

     protected override void OnCreate(Bundle bundle) 
     { 
      base.OnCreate(bundle); 

      // Set our view from the "main" layout resource 
      SetContentView(Resource.Layout.Main); 
      drawerLayout = FindViewById<DrawerLayout>(Resource.Id.drawer_layout); 

      // Init toolbar 
      var toolbar = FindViewById<Android.Support.V7.Widget.Toolbar>(Resource.Id.app_bar); 
      SetSupportActionBar(toolbar); 
      SupportActionBar.SetTitle(Resource.String.app_name); 
      SupportActionBar.SetDisplayHomeAsUpEnabled(true); 
      SupportActionBar.SetDisplayShowHomeEnabled(true); 

      // Attach item selected handler to navigation view 
      var navigationView = FindViewById<NavigationView>(Resource.Id.nav_view); 
      navigationView.NavigationItemSelected += NavigationView_NavigationItemSelected; 

      // Create ActionBarDrawerToggle button and add it to the toolbar 
      var drawerToggle = new ActionBarDrawerToggle(this, drawerLayout, toolbar, Resource.String.open_drawer, Resource.String.close_drawer); 
      drawerLayout.SetDrawerListener(drawerToggle); 
      drawerToggle.SyncState(); 
     } 

void NavigationView_NavigationItemSelected(object sender, NavigationView.NavigationItemSelectedEventArgs e) 
{ 
    var ft = FragmentManager.BeginTransaction(); 
    ft.AddToBackStack(null); 

    switch (e.MenuItem.ItemId) 
    { 
     case (Resource.Id.nav_incidents): 
      SupportActionBar.SetTitle(Resource.String.toolbar_Test); 
      ft.Add(Resource.Id.HomeFrameLayout, new Test()); 
      break; 
    } 

    ft.Commit(); 

    ft.Dispose(); 

    // Close drawer 
    drawerLayout.CloseDrawers(); 
} 

片段

[Activity(Label = "Test")] 
    public class Test : Fragment 
    { 
     public override View OnCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) 
     { 
      View view = inflater.Inflate(Resource.Layout.Test, container, false); 

     return view; 
     } 
    } 

Xamarin探查

enter image description here

+2

什麼是'logcat'輸出,當它崩潰,因爲我沒有看到一個1/2 MB的字符串作爲從你所表現出來的原因。 (我確實看到你正在創建片段而沒有檢查片段是否已經存在)。 – SushiHangover

回答

1

你必須檢查片段可以添加新的

switch (e.MenuItem.ItemId) 
{ 
    case (Resource.Id.nav_incidents): 
     SupportActionBar.SetTitle(Resource.String.toolbar_Test); 
     Fragment myFragment = 
     (Fragment)FragmentManager.FindFragmentByTag("FRAGMENT1"); 
     if (myFragment.IsVisible){ 
      ft.Replace(Resource.Id.HomeFrameLayout, new Test(),"FRAGMENT1"); 
     }else{ 
      ft.Add(Resource.Id.HomeFrameLayout, new Test(),"FRAGMENT1"); 
     } 
     break; 
} 

希望在此之前幫助

+0

這產生了巨大的影響,並解決了我的問題。非常感謝你。 –

+0

@chosenOneThabs你的好來,這個社區是互相幫助的,我很高興我能幫你解決你的問題... –