mgabz
mgabz

Reputation: 733

Is it possible to allow a fragment to rotate and not the parent activity?

I have an Activity and a fullscreen fragment, which inherits from AppCompatDialogFragment. A static instance is created on the Activity and the Show method is called to launch it.

I'd like the fragment to be able to rotate but not the Activity.

I tried setting the Requested Orientation of the activity to 'Portrait' in the override of OnCreate, and setting it again to 'Unspecified' in the OnCreate of the fragment. The issue is that when the screen is rotated, the Activity is recreated and the OnCreate of the fragment is called before the OnCreate of the Activity.w

Any help appreciated.

Upvotes: 2

Views: 1133

Answers (1)

Elvis Xia - MSFT
Elvis Xia - MSFT

Reputation: 10841

I have an Activity and a fullscreen fragment, which inherits from AppCompatDialogFragment. A static instance is created on the Activity and the Show method is called to launch it.

I'd like the fragment to be able to rotate but not the Activity.

Just give a value to the fragment's Rotation will do the trick:

public class MainActivity : AppCompatActivity
{
    AppCompatDialogFragment testFragment;
    protected override void OnCreate(Bundle savedInstanceState)
    {
        base.OnCreate(savedInstanceState);

        // Set our view from the "main" layout resource
        SetContentView(Resource.Layout.Main);
        testFragment = new TestFragment();
        testFragment.Show(SupportFragmentManager, "abc");
    }
 }

And in the Fragment I set a button, when click I set the Rotation of the Fragment to be increased by 5:

public class TestFragment : AppCompatDialogFragment
{
    Button btnClick;
    public override void OnCreate(Bundle savedInstanceState)
    {
        base.OnCreate(savedInstanceState);

        // Create your fragment here
    }

    public override View OnCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
    {
        // Use this to return your custom view for this Fragment
        // return inflater.Inflate(Resource.Layout.YourFragment, container, false);

       View view=inflater.Inflate(Resource.Layout.test_fragment, container, false);
        btnClick = view.FindViewById<Button>(Resource.Id.btnClick);
        btnClick.Click += BtnClick_Click;
        return view;
    }

    private void BtnClick_Click(object sender, EventArgs e)
    {
        this.View.Rotation += 5f;
    }
}

Notes: You will have to manage the fragment's size in case the views runs out of boundary after rotation.

Upvotes: 1

Related Questions