Locking phone in portrait mode

五迷三道 提交于 2019-12-25 02:27:12

问题


I want to change the rotation mode in my application programmatically. All the discussions I found were about disabling rotation in specific Activities. I want to lock the whole phone in portrait mode. How do I accomplish this?

Edit. To clarify, I want to lock the whole phone including all other apps, settings etc. Not just my own app.


回答1:


Add the following to your Activities onCreate:

setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);



回答2:


The easiest, fastest, and guaranteed-to-work way to do this is to define a parent Activity class:

public class MyActivity extends Activity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
    }
}

and then have all your activities inherit the parent Activity:

Activity 1:

public class MainActivity extends MyActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }
}

Activity 2:

public class LoginActivity extends MyActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
    }
}

This way, you only need to define it once.




回答3:


In your AndroidManifest.xml set...

android:screenOrientation="portrait"

...as an attribute for your Activity/Activities.




回答4:


This post should be enough to answer your question :)

stackoverflow.com/questions/582185/

If you are working with fragments you just have to define this once else you need to define it in each activity tag...



来源:https://stackoverflow.com/questions/20042481/locking-phone-in-portrait-mode

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!