При навигации в приложении создается Activity1, которая добавляет на экран Fragment1. Вызов Activity1:
Intent intent = new Intent(this, typeof(Activity1));
StartActivity(intent);
При закрытии фрагмента вызывается:
Activity.Finish();
1) Если в фрагменте вызвать Activity.Finish(), затем заново создать Activity1 через Intent, то fragment1.Activity == null. Почему это происходит?
2) Можно ли это избежать, используя одну активити на все фрагменты, а не создавая для каждого фрагмента свою активити?
Код Fragment1
public class Fragment1: Fragment
{
static View view;
public static Fragment1 NewInstance()
{
var fragment = new Fragment1();
return fragment;
}
public override View OnCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
if (view == null)
{
view = inflater.Inflate(Resource.Layout.fragmentLayout, container, false);
Button buttonNewActivity = view.FindViewById<Button>(Resource.Id.button1);
buttonNewActivity.Click += ButtonNewActivity_Click;
Button buttonCloseActivity = view.FindViewById<Button>(Resource.Id.button2);
buttonCloseActivity.Click += ButtonCloseActivity_Click;
}
else
{
if (view.Parent != null)
((ViewGroup)view.Parent).RemoveView(view);
}
return view;
}
private void ButtonCloseActivity_Click(object sender, EventArgs e)
{
if (Activity != null)
{
Activity.Finish();
}
else
{
// Попадаем сюда при втором вызове activity
}
}
private void ButtonNewActivity_Click(object sender, EventArgs e)
{
if (Activity != null)
{
Intent intent = new Intent(Activity, typeof(Activity2));
StartActivity(intent);
}
else
{
// Попадаем сюда при втором вызове activity
}
}
}
Код Activity1
public class Activity1 : Activity
{
Fragment1 fragment;
private static String fragment_tag = "fragment_tag";
protected override void OnCreate(Bundle savedInstanceState)
{
base.OnCreate(savedInstanceState);
if (this.Resources.Configuration.Orientation != Android.Content.Res.Orientation.Landscape)
{
fragment = FragmentManager.FindFragmentByTag<Fragment1>(fragment_tag);
if (fragment == null)
{
fragment = Fragment1.NewInstance();
}
FragmentManager.BeginTransaction().Replace(Android.Resource.Id.Content, fragment, fragment_tag).Commit();
}
else
Finish();
}
}