How can I set Orientation Fixed for all activities

后端 未结 5 1981
半阙折子戏
半阙折子戏 2020-12-09 23:20

Android Layout. How can I set Orientation Fixed for all activities in application Tag of AndroidMainfest.xml ? I don\'t want to set orientation for each activity individuall

相关标签:
5条回答
  • 2020-12-09 23:44

    If you write your project with generics.

    And you have something like "BaseActivity" than inside onCreate it you can write code like that:

    For Example: BaseActivity extends AppCompatActivity, later you use YourActivity extends BaseActivity

    Portrait

    this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
    

    Landscape

    this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
    
    0 讨论(0)
  • 2020-12-09 23:54

    (Monodroid/C# code)

    You can create an abstract base class

    public abstract class ActBase : Activity
    {
        protected override void OnCreate(Bundle bundle)
        {
            base.OnCreate(bundle);
            RequestedOrientation = clsUtilidades.GetScreenOrientation();
        }
     }
    

    Then all your activities must inherit this class instead Activity

    Somehting like

    [Activity(Label = "Orders", ConfigurationChanges = ConfigChanges.Orientation | ConfigChanges.Keyboard | ConfigChanges.Mcc | ConfigChanges.Mnc)]
    public class ActOrders : ActBase
    {
      ....
    

    This way avoids call the ActivityHelper in your events

    0 讨论(0)
  • 2020-12-09 23:58

    I got the best solution. You don't have to pass any activity as parameter and stuff.

    Here's what you have to do.

    Create a class and extend your application like this. Implement onActivityCreated and onActivityStarted and add the code that sets the orientation to whichever you want.

    public class OldApp extends Application {
    
        @Override
        public void onCreate() {
            super.onCreate();
    
            // register to be informed of activities starting up
            registerActivityLifecycleCallbacks(new ActivityLifecycleCallbacks() {
    
                @Override
                public void onActivityStarted(Activity activity) {
                    activity.setRequestedOrientation(
                            ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
                }
    
                @Override
                public void onActivityResumed(Activity activity) {
    
                }
    
                @Override
                public void onActivityPaused(Activity activity) {
    
                }
    
                @Override
                public void onActivityStopped(Activity activity) {
    
                }
    
                @Override
                public void onActivitySaveInstanceState(Activity activity, Bundle bundle) {
    
                }
    
                @Override
                public void onActivityDestroyed(Activity activity) {
    
                }
    
                @Override
                public void onActivityCreated(Activity activity,
                                              Bundle savedInstanceState) {
                  activity.setRequestedOrientation(
                            ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
                  }
            });
        }
    }
    

    After this, add the following in your Manifest file inside the <application block>:

    android:name=".OldApp"
    

    End result will be like this:

    <application
        android:name=".OldApp"
        ...other values... >
        <activity
            android:name=".SomeActivity"></activity>
    </application>
    
    0 讨论(0)
  • 2020-12-10 00:05

    The GoogleIO app has a ActivityHelper class. It has a static method called initialize() which handles a lot things that happen for every Activity. Then it is just 1 line of code in the onCreate() method that you need to remember, that could handle setting that value and several others that are necessary for each activity.

    Edit: No importing or anything like that. Create a class called ActivityHelper

    public class ActivityHelper {
        public static void initialize(Activity activity) {
            //Do all sorts of common task for your activities here including:
    
            activity.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
        }
    }
    

    Then in all of your activies onCreate() method call ActivityHelper.initialize() If you are planning on developing for tables as well you may want to consider using:

    setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_NOSENSOR);
    

    I wrote more about this here

    Edit: Sorry... you need to pass the the Activity. see the code above

    0 讨论(0)
  • 2020-12-10 00:10

    The accepted answer, and anything suggesting setRequestedOrientation, is far from perfect, because, as stated in documentation, calling setRequestedOrientation at runtime may cause the activity to be restarted, which among other things, affects animations between the screens.

    If possible, the best is to set the desired orientation in AndroidManifest.xml. But since it's error prone to rely on each developer to remember to modify the manifest when adding a new activity, it can be done at build time, by editing AndroidManifest file during the build.

    There are some caveats to editing AndroidManifest this way that you need to be aware of though:

    • If you have some <activity-alias> entries in the output manifest, you should match <activity(?!-) instead of <activity to avoid modifying those (and use replaceAll, which matches regex, instead of replace, which matches string)
    • Be careful to not match the activities that are out of your control. See facebook + android : Only fullscreen opaque activities can request orientation

    My requirement was to update all activities to have fixed orientation, but only in release builds. I achieved it with a bit of code in build.gradle which does simple string replacement in AndroidManifest (assuming that none of the activities has orientation specified already):

    Android Studio 3.0 compatible solution example (touching only activities that match com.mycompany.*):

    android.applicationVariants.all { variant ->
        variant.outputs.all { output ->
            if (output.name == "release") {
                output.processManifest.doLast {
                    String manifestPath = "$manifestOutputDirectory/AndroidManifest.xml"
                    def manifestContent = file(manifestPath).getText('UTF-8')
                    // replacing whitespaces and newlines between `<activity>` and `android:name`, to facilitate the next step
                    manifestContent = manifestContent.replaceAll("<activity\\s+\\R\\s+", "<activity ")
                    // we leverage here that all activities have android:name as the first property in the XML
                    manifestContent = manifestContent.replace(
                            "<activity android:name=\"com.mycompany.",
                            "<activity android:screenOrientation=\"userPortrait\" android:name=\"com.mycompany.")
                    file(manifestPath).write(manifestContent, 'UTF-8')
                }
            }
        }
    }
    

    Android Studio 2.3 compatible solution example (matching all activities, but not matching <activity-alias> entries):

    android.applicationVariants.all { variant ->
        variant.outputs.each { output ->
            if (output.name == "release") {
                output.processManifest.doLast {
                    def manifestOutFile = output.processManifest.manifestOutputFile
                    def newFileContents = manifestOutFile.getText('UTF-8')
                            .replaceAll(/<activity(?!-)/, "<activity android:screenOrientation=\"userPortrait\" ")
                    manifestOutFile.write(newFileContents, 'UTF-8')
                }
            }
        }
    }
    

    I used userPortrait instead of portrait as I prefer to give the user more flexibility.

    The above works out of the box if you just have variants (debug, release). If you additionally have flavors, you might need to tweak it a bit.

    You might want to remove if (output.name == "release") depending on your needs.

    0 讨论(0)
提交回复
热议问题