Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Where to best use setRequestedOrientation inside a Fragment?

I want to use setRequestedOrientation( ActivityInfo.SCREEN_ORIENTATION_PORTRAIT); inside a class that extends Fragmnet, where it should be best used? inside onCreateView(), onActivityCreated or onCreate()? and how? because when I tried to use it, eclipse underline it with red squiggle.

like image 264
user2121 Avatar asked Jun 26 '14 12:06

user2121


People also ask

How to include a Fragment in an activity?

Add a fragment to an activity You can add your fragment to the activity's view hierarchy either by defining the fragment in your activity's layout file or by defining a fragment container in your activity's layout file and then programmatically adding the fragment from within your activity.

How to work with Fragments in Android studio?

We can use Android Studio support in the Design view for the MainActivity layout file to select a fragment from inside the Custom choices. Open the activity_main layout file in design view and, inside the Palete, click Fragment under the “Custom” section. You will be prompted to select a fragment.

How to add Fragment in activity in Android programmatically?

To programmatically add or remove a Fragment, you will need the FragmentManager and FragmentTransaction instances. Simply stated and per the Android documentation, a FragmentManager manages the fragments in an Activity. Obtain the FragmentManager by calling getFragmentManager( ) in an Activity.


2 Answers

I think you should precede

setRequestedOrientation( ActivityInfo.SCREEN_ORIENTATION_PORTRAIT); with getActivity() so you can get instance of the current activity your Fragment is associated with.

And, I think you could use it inside onCreateView()

like image 83
LetsamrIt Avatar answered Oct 06 '22 08:10

LetsamrIt


You can use it inside of onCreateView() by calling your activity like thi

Activity a = getActivity();
    if(a != null) a.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);

A note here is that it changes your activites orientation when this fragment is called. You cannot change the orientation of a fragment, but you can change the orientation of the activity from a fragment.

like image 22
user3331142 Avatar answered Oct 06 '22 08:10

user3331142