我正在用Xamarin制作一个android应用。在我的一项活动中,我有一个放置碎片的框架布局。在事务中,我使用SetCustomAnimations()
,Replace()
和AddToBackStack()
。当我按下“后退”按钮或调用OnBackPressed()
时,应用程序崩溃,但出现以下异常:
Java.Lang.IllegalStateException:指定的子代已经有一个父代。 您必须先在孩子的父母上调用removeView()。
如果我删除对SetCustomAnimations()
的调用,它可以工作,但是我没有任何动画。
活动:
[Android.App.Activity(Label = "Login")]
public class LoginActivity : AppCompatActivity
{
private FrameLayout view;
protected override void OnCreate(Bundle savedInstanceState)
{
base.OnCreate(savedInstanceState);
view = new FrameLayout(this)
{
Id = View.GenerateViewId()
};
SetContentView(view);
SupportFragmentManager.BeginTransaction().Add(view.Id, SelectDomainFragment.Create()).Commit();
}
public void ShowFragment(Fragment fragment)
{
SupportFragmentManager.BeginTransaction()
.SetCustomAnimations(Resource.Animation.enter_right, Resource.Animation.exit_left, Resource.Animation.enter_left, Resource.Animation.exit_right)
.Replace(view.Id, fragment)
.AddToBackStack(null)
.Commit();
}
}
SelectDomainFragment:
public class SelectDomainFragment : Fragment
{
private SelectDomainView view;
public static SelectDomainFragment Create() => new SelectDomainFragment();
public override void OnCreate(Bundle savedInstanceState)
{
base.OnCreate(savedInstanceState);
view = new SelectDomainView(Context);
view.CloudButtonClicked += (sender, e) => ToLogin(1);
view.OnPremButtonClicked += (sender, e) => ToLogin(2);
}
public override View OnCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) => view;
private void ToLogin(int target) => ((LoginActivity)Activity).ShowFragment(LoginFragment.Create(target));
}
LoginFragment:
public class LoginFragment : Fragment
{
private LoginView view;
public static LoginFragment Create(int target)
{
var args = new Bundle();
args.PutInt("target", target);
return new LoginFragment
{
Arguments = args
};
}
public override void OnCreate(Bundle savedInstanceState)
{
base.OnCreate(savedInstanceState);
view = new LoginView(Context);
}
public override View OnCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) => view;
}