简体   繁体   English

在View类中锁定屏幕方向-Android

[英]Lock screen orientation within View class - Android

I know how to do this within the activity class, however this doesn't fit my need. 我知道如何在活动课程中执行此操作,但这不符合我的需求。 Within my class that extends View, once a method is called i would like the screen orientation to be locked. 在扩展View的类中,一旦调用了一个方法,我希望锁定屏幕方向。 And then once another method is called i would like it to be unlocked. 然后,一旦调用了另一种方法,我希望将其解锁。

Is there a way i can do this within my class that extends View? 有没有一种方法可以在我的类中扩展View?

Thanks. 谢谢。

@Override
public void onConfigurationChanged(Configuration newConfig) {
    // TODO Auto-generated method stub
    super.onConfigurationChanged(newConfig);

    setContentView(this.gameView);

    if (this.gameView.isOrientationChange() == false) {
        // Stop the screen orientation changing during an event
        switch (this.getResources().getConfiguration().orientation) {
            case Configuration.ORIENTATION_PORTRAIT:
                this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
                break;
            case Configuration.ORIENTATION_LANDSCAPE:
                this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
                break;
        }
    }
    else {
        // allow screen rotations
        this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED);
    }
}

In the class extending View, there is an orientationChange boolean field. 在扩展View的类中,有一个directionChange布尔字段。 this is changed by method indicating whether the devices orientation can be changed. 这通过指示是否可以更改设备方向的方法来更改。 This worked but the screen size also changes when the orientation is changed. 这可行,但是当改变方向时屏幕尺寸也会改变。 So if there is a lot of code dependent on the size and is timed, then this may cause more problems than solve. 因此,如果有很多代码取决于大小并且是定时的,那么这可能会导致更多的问题而不是解决。

我认为您正在寻找的是configChanges,请参阅doc-> http://developer.android.com/reference/android/R.attr.html#configChanges

Maybe I've got a method, just write down that: 也许我有一个方法,只需写下:

set layoutParams.screenOrientation value into: ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED or ActivityInfo.SCREEN_ORIENTATION_LOCKED layoutParams.screenOrientation值设置为: ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIEDActivityInfo.SCREEN_ORIENTATION_LOCKED

Then, call addView or updateViewLayout to update this LayoutParams. 然后,调用addViewupdateViewLayout来更新此LayoutParams。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM