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 device , but it once changes the orientation and later on does not change the orientation. here is my code please help
public class Hls extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_hls);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
}
@Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
Log.v("new orientation", "yes");
if (newConfig.orientation == Configuration.ORIENTATION_PORTRAIT)
{
Toast.makeText(this, "portrait", Toast.LENGTH_LONG).show();
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
}
if (newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE)
{
Toast.makeText(this, "landscape", Toast.LENGTH_LONG).show();
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
}
}
On this statement
also in
onCreate(Bundle bundle);
You called
or
It means that your activity is in landscape/portrait orientation and never rotate again
removing it will trigger the
onConfigurationChanged(Configuration)
againI'm not clear about your requirement. If you don't mind restarting your activity, you can just skip overriding
onConfigurationChanged
. System will handle Orientation changes for you. In case you don't want it to be restarted on orientation changes, just mention<activity android:configChanges="keyboardHidden|orientation|screenSize"/>
, and overrideonConfigurationChanged
and callsetContentView()
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:-
and in the manifest add android:configChanges="orientation" in activity :-
Sample layout for activity_hls_port :-
Sample for landscape mode:-