Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
284 views
in Technique[技术] by (71.8m points)

java - Activity orientation changes automatically on Android

I'm developing a mobile application based on Android with minSdkVersion=15. I would like to support both orientations for tablets and only portrait for smartphones. Everything works like a charm but I'm experiencing a little bug that is driving me crazy. When smartphone is in landscape mode and I try to trigger a new Activity, it opens in landscape mode for a while and then autorotates to portrait. Each one of my activities extend a GeneralActivity class:

public class GeneralActivity extends Activity {
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // If smartphone lock orientation to portrait
        if (!Helper.isTablet(this.getApplicationContext())){
            this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
        }
    }
}

I detect tablets with this function:

public class Helper {
    public static boolean isTablet(Context context){
        Configuration config = context.getResources().getConfiguration()
        return config.smallestScreenWidthDp >= 600;
    }
}

I choose not to specify android:screenOrientation inside Manifest.xml because in that way I'm able to support all interface orientation for tablets. Am I missing something?

EDIT

I decided to apply the best practice suggested in the answer by Jonathan, but the issue I described is still here. Here's my repo on github: https://github.com/giacmarangoni/Android-Orientation-Test

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

I had the same problem on Android N & O and found a solution.

I still use setRequestedOrientation in the onCreate method, but I've added this for every activity in the manifest:

android:screenOrientation="behind"

This makes sure that the activity launches with the same orientation as the previous activity. The setRequestedOrientation afterwards will override it, but if it's the same as the previous activity you don't see anything change as the user.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...