如何为所有活动设置固定方向

发布于 2024-11-18 07:31:18 字数 78 浏览 1 评论 0 原文

安卓布局。如何为 AndroidMainfest.xml 的应用程序标签中的所有活动设置固定方向? 我不想单独为每个活动设置方向。 提前致谢。

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 individually.
Thanks in advance.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

伴随着你 2024-11-25 07:31:18

GoogleIO 应用有一个 ActivityHelper 类。它有一个名为 initialize() 的静态方法,它处理每个 Activity 发生的许多事情。然后,您只需记住 onCreate() 方法中的 1 行代码,即可处理设置该值以及每个活动所需的其他几个值。

编辑: 禁止导入或类似操作。创建一个名为 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);
    }
}

,然后在所有活动的 onCreate() 方法中调用 ActivityHelper.initialize()
如果您也计划开发表格,您可能需要考虑使用:

setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_NOSENSOR);

我写了更多关于此的内容 这里

编辑: 抱歉...您需要传递 Activity。参见上面的代码

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

靑春怀旧 2024-11-25 07:31:18

接受的答案以及任何建议 setRequestedOrientation 的内容都远非完美,因为 如文档中所述在运行时调用 setRequestedOrientation 可能会导致 Activity 重新启动,这会影响动画屏幕之间。

如果可能,最好是在 AndroidManifest.xml 中设置所需的方向。
但是,由于依赖每个开发人员在添加新活动时记住修改清单很容易出错,因此可以在构建时通过在构建期间编辑 AndroidManifest 文件来完成。

不过,以这种方式编辑 AndroidManifest 时需要注意一些注意事项:

我的要求是更新所有活动以具有固定方向,但是仅在发布版本中。我通过 build.gradle 中的一些代码实现了它,该代码在 AndroidManifest 中进行了简单的字符串替换(假设没有一个 Activity 已指定方向):

Android Studio 3.0 兼容解决方案示例(仅涉及与 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 兼容解决方案示例(匹配所有活动,但不匹配 条目):

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')
            }
        }
    }
}

我使用 userPortrait 而不是 portrait,因为我更喜欢为用户提供更大的灵活性。

如果您只有变体(调试、发布),上面的方法是开箱即用的。如果你还有口味,你可能需要稍微调整一下。

您可能需要根据需要删除 if (output.name == "release")

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:

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.

淑女气质 2024-11-25 07:31:18

如果您使用泛型编写项目。

并且您在onCreate内部有类似“BaseActivity”的内容,您可以编写如下代码:

例如: >
BaseActivity 扩展了 AppCompatActivity,稍后您使用 YourActivity 扩展
BaseActivity

纵向

this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);

横向

this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);

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);
蓝眼睛不忧郁 2024-11-25 07:31:18

(Monodroid/C# 代码)

您可以创建一个抽象基类

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

然后您的所有活动都必须继承这个类,而不是 Activity

这样的

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

方式可以避免在您的事件中调用 ActivityHelper

(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

陌上青苔 2024-11-25 07:31:18

我得到了最好的解决方案。您不必将任何活动作为参数和内容传递。

这是你必须做的。

创建一个类并像这样扩展您的应用程序。
实现 onActivityCreated 和 onActivityStarted 并添加将方向设置为您想要的方向的代码。

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);
              }
        });
    }
}

之后,在 Manifest 文件的 内添加以下内容:

android:name=".OldApp"

最终结果将如下所示:

<application
    android:name=".OldApp"
    ...other values... >
    <activity
        android:name=".SomeActivity"></activity>
</application>

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>
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文