Android Device onConfigurationChanged event does not handling orientation

前端 未结 3 1253
执念已碎
执念已碎 2021-01-13 18:46

i have an activity and on startup of the activity i need to change the orientation in lanscape and then later on i want to handle both orientation changes as user rotates de

3条回答
  •  广开言路
    2021-01-13 19:20

    Using setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE) in onCreate will fix your orientation permanently to landscape and will avoid any change in orientation. That is why your orientation gets fixed and doesn't respond to the rotations.

    Here is an alternative you can use :-

    1> Create two views in your layout. i.e one for landscape and one for portrait views.Lets say activity_hls_land and activity_hls_port.

    2> Use setContentView(R.layout.activity_hls) in onConfigurationChanged(Configuration newConfig) instead of setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE) or setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT)

    Here is the sample code:-

     public class MainActivity extends Activity {
    boolean isLaunched=true;
        @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
    
    
            if(isLaunched){
            Toast.makeText(this, "1 st launch " , Toast.LENGTH_SHORT).show(); 
            setContentView(R.layout.activity_hls_land);
            }
    
        }
    
        @Override
        public void onConfigurationChanged(Configuration newConfig) {
            super.onConfigurationChanged(newConfig);
    
        if (newConfig.orientation == Configuration.ORIENTATION_PORTRAIT)
        {
            Toast.makeText(this, "portrait", Toast.LENGTH_SHORT).show();
            setContentView(R.layout.activity_hls_port);
        }
         if (newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE)
        {
            Toast.makeText(this, "landscape", Toast.LENGTH_SHORT).show();
            setContentView(R.layout.activity_hls_land );
        } 
        }
    
    }
    

    and in the manifest add android:configChanges="orientation" in activity :-

    
    
                
                    
    
                    
                
              
    

    Sample layout for activity_hls_port :-

    
    
        
     
      
    
    

    Sample for landscape mode:-

    
    
        
     
      
    
    

提交回复
热议问题