2016-08-14 54 views
0

等待啓動應用程序。旋轉設備。點擊查看。例外。當設備的方向發生變化時,簡單代碼會拋出IllegalStateException

Project code here

爲什麼我會收到這個異常?

MainActivity.cs

[Activity (Label = "OrientationChangeFragmentCommit", MainLauncher = true, Icon = "@mipmap/icon")] 
public class MainActivity : Activity 
{ 
    const string currentFragmentTag = "currentFragment"; 

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

     SetContentView (Resource.Layout.Main); 

     if (GetCurrentFragment() == null) 
     { 
      BlueFragment frag = new BlueFragment(); 
      frag.AuthTcs.Task.ContinueWith(task => 
      { 
       try 
       { 
        RunOnUiThread(() => FragmentManager.PopBackStackImmediate()); 
       } 
       catch (Exception exc) 
       { 
        //exception here 
       } 
      }); 
      AddFrag(this, frag, Resource.Id.fragmentContainer); 
     } 
    } 

    void AddFrag(Activity act, Fragment frag, int containerId) 
    { 
     FragmentTransaction fragmentTx = act.FragmentManager.BeginTransaction(); 
     fragmentTx.Add(containerId, frag, currentFragmentTag); 
     fragmentTx.AddToBackStack(null); 
     fragmentTx.Commit(); 
    } 

    Fragment GetCurrentFragment() 
    { 
     var f = FragmentManager.FindFragmentByTag (currentFragmentTag); 
     return f; 
    } 
} 

BlueFragment.cs

public class BlueFragment : Fragment 
{ 
    public TaskCompletionSource<bool> AuthTcs = new TaskCompletionSource<bool>(); 
    public override void OnCreate (Bundle savedInstanceState) 
    { 
     base.OnCreate (savedInstanceState); 
     RetainInstance = true; 
    } 

    public override View OnCreateView (LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) 
    { 
     base.OnCreateView (inflater, container, savedInstanceState); 

     var view = new LinearLayout (inflater.Context); 
     view.Orientation = Orientation.Vertical; 
     view.SetBackgroundColor (Color.Blue); 
     ViewGroup.LayoutParams par = new ViewGroup.LayoutParams (ViewGroup.LayoutParams.MatchParent, ViewGroup.LayoutParams.MatchParent); 
     view.LayoutParameters = par; 
     view.AddView(new View(inflater.Context)); 

     view.Click += (s, e) => 
     { 
      AuthTcs.TrySetResult(true); 
     }; 

     return view; 
    } 
} 

Main.axml

<?xml version="1.0" encoding="utf-8"?> 
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 
    android:orientation="vertical" 
    android:layout_width="match_parent" 
    android:layout_height="match_parent"> 
    <FrameLayout 
     android:id="@+id/fragmentContainer" 
     android:layout_width="match_parent" 
     android:layout_height="match_parent" /> 
</LinearLayout> 

異常說:Java.Lang.IllegalStateException:的onSaveInstanceState後無法執行此操作

回答

0

正確的代碼是:

frag.AuthTcs.Task.ContinueWith(task => 
    { 
     RunOnUiThread (() => frag.Activity.FragmentManager.PopBackStackImmediate()); 
    }); 

由於lambda函數存儲對舊活動的引用,因此存儲到舊的FragmentManager。

相關問題