I have come across a problem where the orientation sensorPortrait does not work, i have tried enabling both through the manifest and within the activity itself with
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_SENSOR_PORTRAIT);
But this seems to just be locked in normal portrait mode, however if i try `fullSensor'
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_FULL_SENSOR);
which according to the docs
The orientation is determined by the device orientation sensor for any of the 4 orientations. This is similar to "sensor" except this allows any of the 4 possible screen orientations, regardless of what the device will normally do (for example, some devices won't normally use reverse portrait or reverse landscape, but this enables those). Added in API level 9.
and it does exactly that, all 4 orientations are possible. If i also try
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_REVERSE_PORTRAIT);
I am able to achieve reverse portrait, which leads me back to my original question, why does sensorPortrait not work? It looks like it has something to do with this line from the docs for `fullSensor'
regardless of what the device will normally do (for example, some devices won't normally use reverse portrait or reverse landscape, but this enables those)
So how do i enable it, is that possible and why does fullSensor seem to override it but not sensorPortrait? I can't seem to find any mention of how to do so. This question suggests that the PhoneWindowManager is responsible for this.
Is the ideal solution just to create an OrientationEventListener() and manually call setRequestedOrientation() manually depending on the values returned via onOrientationChanged(int orientation)?
As a work around i have created a SensorPortraitActivity:
public class SensorPortraitActivity extends AppCompatActivity {
private static final int PORTRAIT = 0;
private static final int REVERSE_PORTRAIT = 180;
private static final int OFFSET = 45;
private static final int UNKNOWN = -1;
// account for 0 = 360 (eg. -1 = 359)
private static final int PORTRAIT_START = PORTRAIT - OFFSET + 360;
private static final int PORTRAIT_END = PORTRAIT + OFFSET;
private static final int REVERSE_PORTRAIT_START = REVERSE_PORTRAIT - OFFSET;
private static final int REVERSE_PORTRAIT_END = REVERSE_PORTRAIT + OFFSET;
private OrientationChangeListener mListener;
private OrientationEventListener mOrientationListener;
private CurrentOrientation mCurrentOrientation;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mOrientationListener = new OrientationEventListener(this) {
#Override
public void onOrientationChanged(int i) {
orientationChanged(i);
}
};
}
#Override
protected void onResume() {
super.onResume();
mOrientationListener.enable();
}
#Override
protected void onPause() {
super.onPause();
mOrientationListener.disable();
}
//optional
public void setOrientationChangeListener(OrientationChangeListener listener){
mListener = listener;
}
private void orientationChanged(int degrees) {
if (degrees != UNKNOWN){
if (degrees >= PORTRAIT_START || degrees <= PORTRAIT_END){
if (mCurrentOrientation != CurrentOrientation.PORTRAIT){
mCurrentOrientation = CurrentOrientation.PORTRAIT;
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
if (mListener != null){
mListener.onPortrait();
}
}
} else if (degrees >= REVERSE_PORTRAIT_START && degrees <= REVERSE_PORTRAIT_END){
if (mCurrentOrientation != CurrentOrientation.REVERSE_PORTRAIT){
mCurrentOrientation = CurrentOrientation.REVERSE_PORTRAIT;
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_REVERSE_PORTRAIT);
if (mListener != null) {
mListener.onReversePortrait();
}
}
}
}
}
interface OrientationChangeListener {
void onPortrait();
void onReversePortrait();
}
enum CurrentOrientation {
PORTRAIT, REVERSE_PORTRAIT
}
}
Although it does seem like overkill for something as simple as this.
To use it simple extend SensorPortraitActivity
public class ExampleActivity extends SensorPortraitActivity implements SensorPortraitView.OrientationChangeListener {
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//set listener if you want callbacks
super.setOrientationChangeListener(this);
}
#Override
public void onPortrait() {
//portrait orientation
}
#Override
public void onReversePortrait() {
//reverse portrait orientation
}
}
Related
I have come across a problem where the orientation sensorPortrait does not work, i have tried enabling both through the manifest and within the activity itself with
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_SENSOR_PORTRAIT);
But this seems to just be locked in normal portrait mode, however if i try `fullSensor'
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_FULL_SENSOR);
which according to the docs
The orientation is determined by the device orientation sensor for any of the 4 orientations. This is similar to "sensor" except this allows any of the 4 possible screen orientations, regardless of what the device will normally do (for example, some devices won't normally use reverse portrait or reverse landscape, but this enables those). Added in API level 9.
and it does exactly that, all 4 orientations are possible. If i also try
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_REVERSE_PORTRAIT);
I am able to achieve reverse portrait, which leads me back to my original question, why does sensorPortrait not work? It looks like it has something to do with this line from the docs for `fullSensor'
regardless of what the device will normally do (for example, some devices won't normally use reverse portrait or reverse landscape, but this enables those)
So how do i enable it, is that possible and why does fullSensor seem to override it but not sensorPortrait? I can't seem to find any mention of how to do so. This question suggests that the PhoneWindowManager is responsible for this.
Is the ideal solution just to create an OrientationEventListener() and manually call setRequestedOrientation() manually depending on the values returned via onOrientationChanged(int orientation)?
As a work around i have created a SensorPortraitActivity:
public class SensorPortraitActivity extends AppCompatActivity {
private static final int PORTRAIT = 0;
private static final int REVERSE_PORTRAIT = 180;
private static final int OFFSET = 45;
private static final int UNKNOWN = -1;
// account for 0 = 360 (eg. -1 = 359)
private static final int PORTRAIT_START = PORTRAIT - OFFSET + 360;
private static final int PORTRAIT_END = PORTRAIT + OFFSET;
private static final int REVERSE_PORTRAIT_START = REVERSE_PORTRAIT - OFFSET;
private static final int REVERSE_PORTRAIT_END = REVERSE_PORTRAIT + OFFSET;
private OrientationChangeListener mListener;
private OrientationEventListener mOrientationListener;
private CurrentOrientation mCurrentOrientation;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mOrientationListener = new OrientationEventListener(this) {
#Override
public void onOrientationChanged(int i) {
orientationChanged(i);
}
};
}
#Override
protected void onResume() {
super.onResume();
mOrientationListener.enable();
}
#Override
protected void onPause() {
super.onPause();
mOrientationListener.disable();
}
//optional
public void setOrientationChangeListener(OrientationChangeListener listener){
mListener = listener;
}
private void orientationChanged(int degrees) {
if (degrees != UNKNOWN){
if (degrees >= PORTRAIT_START || degrees <= PORTRAIT_END){
if (mCurrentOrientation != CurrentOrientation.PORTRAIT){
mCurrentOrientation = CurrentOrientation.PORTRAIT;
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
if (mListener != null){
mListener.onPortrait();
}
}
} else if (degrees >= REVERSE_PORTRAIT_START && degrees <= REVERSE_PORTRAIT_END){
if (mCurrentOrientation != CurrentOrientation.REVERSE_PORTRAIT){
mCurrentOrientation = CurrentOrientation.REVERSE_PORTRAIT;
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_REVERSE_PORTRAIT);
if (mListener != null) {
mListener.onReversePortrait();
}
}
}
}
}
interface OrientationChangeListener {
void onPortrait();
void onReversePortrait();
}
enum CurrentOrientation {
PORTRAIT, REVERSE_PORTRAIT
}
}
Although it does seem like overkill for something as simple as this.
To use it simple extend SensorPortraitActivity
public class ExampleActivity extends SensorPortraitActivity implements SensorPortraitView.OrientationChangeListener {
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//set listener if you want callbacks
super.setOrientationChangeListener(this);
}
#Override
public void onPortrait() {
//portrait orientation
}
#Override
public void onReversePortrait() {
//reverse portrait orientation
}
}
Hi I have a floating window in which my floating window serves as the video and it also have a controls inside the video which under the floating window
Now my question is it possible that I can rotate my custom view from floating window only without affecting the orientation of my activity
If someone already tried it please guide me towards it.
Thank you.
I have never done it before. But I have an idea. You can use the below code to get the current orientation of the screen on your device.
OrientationEventListener onrientationEventListener = new OrientationEventListener(context, SensorManager.SENSOR_DELAY_UI) {
#Override
public void onOrientationChanged(int rotation) {
Logger.e("Orientation: " + rotation);
}
};
And after that, depends on the value of "rotation", you can use rotate animation in Android to rotate your custom view.
#Beginer: Here is the code I implemented it. I used the above code in my custom view in my small camera app. It helps me to know which degree should I rotate the bitmap after taken. The toScreenOrientation() method bellow return a value in degrees (0, 90, 180, 270) you also modify it by yourself(whatever you want).
Using setOrientationChangedListener() method to help the parent(Activity, Fragment, etc.) receives a callback also.
public class TakePhotoView extends ConstraintLayout {
private static final int SCREEN_ORIENTATION_0 = 0;
private static final int SCREEN_ORIENTATION_90 = 90;
private static final int SCREEN_ORIENTATION_180 = 180;
private static final int SCREEN_ORIENTATION_270 = 270;
private OnOrientationChangedListener mOnOrientationChangedListener;
private OrientationEventListener mOrientationEventListener;
private int mScreenRotation;
public TakePhotoView(Context context) {
this(context, null);
}
public TakePhotoView(Context context, AttributeSet attrs) {
super(context, attrs);
//....do something here
mOrientationEventListener = new OrientationEventListener(context, SensorManager.SENSOR_DELAY_UI) {
#Override
public void onOrientationChanged(int rotation) {
Logger.e("Orientation: " + rotation);
if (rotation == OrientationEventListener.ORIENTATION_UNKNOWN) {
mScreenRotation = DEFAULT_SCREEN_ROTATION;
return;
}
mScreenRotation = rotation;
if(mOnOrientationChangedListener != null){
mOnOrientationChangedListener.onOrientationChanged(rotation);
}
}
};
}
private void takePhoto(Camera camera) {
if (camera != null) {
camera.takePicture(null, null, mPictureCallback);
}
}
private Camera.PictureCallback mPictureCallback = new Camera.PictureCallback() {
#Override
public void onPictureTaken(byte[] data, Camera camera) {
final int screenRotation = mScreenRotation;
int rotate = toScreenOrientation(screenRotation);
// Rotate/Flip the bitmap depends on the 'rotate' value
}
};
/**
* Converts sensor rotation in degrees to screen orientation constants.
*
* #param rotation sensor rotation angle in degrees
* #return Screen orientation angle in degrees (0, 90, 180, 270).
*/
private int toScreenOrientation(int rotation) {
if (rotation > 290 || rotation <= 70) {
return SCREEN_ORIENTATION_0;
} else if (rotation > 70 && rotation <= 110) {
return SCREEN_ORIENTATION_90;
} else if (rotation > 110 && rotation <= 250) {
return SCREEN_ORIENTATION_180;
} else {
return SCREEN_ORIENTATION_270;
}
}
public void setOrientationChangedListener(OnOrientationChangedListener orientationChangedListener){
this.mOnOrientationChangedListener = orientationChangedListener;
}
////////////////////////////////////////////////////////////////////////////////////////////////
// Interfaces
////////////////////////////////////////////////////////////////////////////////////////////////
public interface OnOrientationChangedListener {
void onOrientationChanged(int rotation);
}
}
Can I use this listener even I disable rotation in my manifest?
-> It still works fine.
Hope it helps.
Looks like you do not want your Activity to be recreated on device rotation.
If so, then add configChanges attribute in AndroidManifest:
<activity
...
android:configChanges="orientation" >
This will stop activity recreation on rotation. But in your activity you can check that device has been rotated in onConfigurationChanged() method:
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
// Checks the orientation of the screen
if (newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE) {
...
} else if (newConfig.orientation == Configuration.ORIENTATION_PORTRAIT){
...
}
}
Do not forget to read android developer guides. ;)
I have found a way to do this but I used alertDailog. The logic will be the same for all views.
AlertDialog dialog;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.stack_overflow2);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
AlertDialog.Builder alert123 = new AlertDialog.Builder(StackOverflow2.this);
View current_view = getLayoutInflater().inflate(R.layout.password_alert,null);
l2 = current_view.findViewById(R.id.linearView);
// Here l2 is linear layout getting root layout of password_alert
alert123.setView(current_view);
dialog = alert123.create();
dialog.show();
OrientationEventListener onrientationEventListener = new OrientationEventListener(getBaseContext(), SensorManager.SENSOR_DELAY_UI) {
#Override
public void onOrientationChanged(int rotation) {
Log.e("Orientation: " , String.valueOf(rotation));
if(rotation==270 || rotation==90)
{
if(rotation==270)
{
l2.setRotation(90);
}
else
{
l2.setRotation(270);
}
dialog.getWindow().setLayout(ViewGroup.LayoutParams.WRAP_CONTENT,ViewGroup.LayoutParams.WRAP_CONTENT);
Toast.makeText(StackOverflow2.this, "Change Dialog Rotation", Toast.LENGTH_SHORT).show();
}
else
{
if(rotation==180)
{
l2.setRotation(180);
}
else
{
l2.setRotation(0);
}
Toast.makeText(StackOverflow2.this, "Normal Display to Occur", Toast.LENGTH_SHORT).show();
}
}
};
if (onrientationEventListener.canDetectOrientation()) {
Log.v("ORIE", "Can detect orientation");
onrientationEventListener.enable();
} else {
Log.v("ORIE", "Cannot detect orientation");
onrientationEventListener.disable();
}
}
Here are some pictures :
0 Degree
90 Degree
270 Degree
As you can see the background activity is in potrait mode always. The alert dialog's height and width is a little off but you can change your view's dimensions differently. I hope this code solves your problem.
How to rotate a dialog fragment 90 or 180 degrees if the activity screen orientation is locked?
Activity declared in manifest:
<activity
...
android:screenOritentation="landscape" />
Dialog fragment:
public class MyFragment extends DialogFragment{
// stuff
}
I've rotated the dialog's layout using NineOldAndroid library. It is working as I expected if I rotate to 180 degree, however if I rotate to 90 degree, the layout is not visible entirely.
I am trying to rotate the entire dialog (not only the layout), inclusive buttons, title, everything, but I couldn't figured out how to to that.
Main idea that You can try use some flags of ActivityInfo on methods onStart() and onStop() at DialogFragment.
For example for DialogFragment you can fix some orientation on onStart() method:
#Override
public void onStart()
{
super.onStart();
// lock screen;
DisplayTools.Orientation orientation = DisplayTools.getDisplatOrientation(getActivity());
getActivity().setRequestedOrientation(orientation == DisplayTools.Orientation.LANDSCAPE
? ActivityInfo.SCREEN_ORIENTATION_SENSOR_LANDSCAPE
: ActivityInfo.SCREEN_ORIENTATION_SENSOR_PORTRAIT);
}
(this use something flags from ActivityInfo)
And restore orientation on onStop() method:
#Override
public void onStop()
{
super.onStop();
// unlock screen;
getActivity().setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED);
}
(on your particular case you must use ActivityInfo.SCREEN_ORIENTATION_SENSOR_LANDSCAPE instead ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED at onStop() method)
Where
public class DisplayTools
{
static public Point getDisplaySize(Context context)
{
WindowManager wm = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
Display display = wm.getDefaultDisplay();
Point size = new Point();
display.getSize(size);
return size;
}
static public Orientation getDisplatOrientation(Activity activity)
{
if (activity != null)
{
int orientation = activity.getResources().getConfiguration().orientation;
if (orientation == Configuration.ORIENTATION_LANDSCAPE)
{
return Orientation.LANDSCAPE;
}
if (orientation == Configuration.ORIENTATION_PORTRAIT)
{
return Orientation.PORTRAIT;
}
if (orientation == Configuration.ORIENTATION_UNDEFINED)
{
return Orientation.UNDEFINED;
}
}
return Orientation.UNKNOWN;
}
public static enum Orientation
{
UNKNOWN(-1),
UNDEFINED(0),
PORTRAIT(1),
LANDSCAPE(2);
private int tag;
Orientation(int i)
{
this.tag = i;
}
}
}
I hope you understand main idea!
The solution is to inflate a specific layout for the dialog by the current orientation. In my app, the activity is locked to landscape, however, if I turn the device to portrait I am showing a specific layout without recreating the activity.
Note: It is not working with an already opened dialog. The dialog is not rotated when the device is rotated. It is rotated only at creation at the dialog.
Your activity:
public class ActivityMain extends Activity
{
private boolean isPortrait = false;
private boolean isFlip = false;
private OrientationEventListener orientationEventListener;
#Override
protected void onCreate(Bundle bundle)
{
// stuff
setUpOrientationListener();
}
// Register device to detected orientation change
private void setUpOrientationListener()
{
orientationEventListener = new OrientationEventListener(this, SensorManager.SENSOR_DELAY_NORMAL)
{
#Override
public void onOrientationChanged(int orientation)
{
// Device is in portrait
if (orientation > 320 || orientation < 45)
{
if (!isPortrait)
onPortraitRotation();
}
else // Device is flipped
if (orientation > 45 && orientation < 145)
{
if (!isFlip)
onFlipRotation();
}
else // Device is in landscape
{
if (isPortrait)
onLandscapeRotation();
}
}
};
// If device is capable for detecting orientation register listener
if (orientationEventListener.canDetectOrientation())
orientationEventListener.enable();
}
private void onPortraitRotation()
{
isPortrait = true;
isFlip = false;
}
private void onFlipRotation()
{
isFlip = true;
isPortrait = false;
}
private void onLandscapeRotation()
{
isPortrait = false;
isFlip = false;
}
// Creates your custom dialog
private void showCustomDialog()
{
MyDialog dialog = new MyDialog(ActivityMain.this, isPortrait, isFlipped);
dialog.show();
}
}
Now we know the orientation of our device, now create the dialog.
NOTE Use DialogFragment with a static constructor: http://developer.android.com/reference/android/app/DialogFragment.html (however, I am using simple Dialog for demonstration)
public class MyDialog extends Dialog
{
private boolean isPortrait;
private boolean isFlipped;
public MyDialog(Context context, boolean isPortrait, boolean isFlipped)
{
super(context);
this.isPortrait = isPortrait;
this.isFlipped = isFlipped;
}
#Override
protected void onCreate(Bundle bundle)
{
super.onCreate(savedInstanceState);
getWindow().requestFeature(Window.FEATURE_NO_TITLE);
// Device is in landscape mode
if (!isPortrait && !isFlipped)
setContentView(R.layout.dialog_landscape);
else
if (isPortrait && !isFlipped) // Device is in portrait
setContentView(R.layout.dialog_vertical);
else // Device is flipped
{
setContentView(R.layout.dialog_landscape);
// Rotate the entire root layout
View layout = findViewById(R.id.rlContainer);
ObjectAnimator.ofFloat(layout, "rotation", 180).setDuration(0).start();
}
}
}
For rotation use NindeOldAndroids library.
NOTE: This solution is working for: landscape, portrait and flipped landscape. To show flipped portrait you must calculate the orientation in the orientation detect listener.
NOTE 2: Do not use system buttons! They are attached to the dialog which is attached to the parent (activity) locked orientation. Use layout-built-in button views.
I think cosic's solution is the best, along with this Activity configuration:
android:configChanges="orientation|screenSize"
...then in your Activity you can implement onConfigurationChanged(), and either ignore the change or do something custom.
I have an Android application using LinearLayout as main layout with a SurfaceView filled by camera preview.
In this I inflate another LinearLayout with three Buttons and a custom TextView. I would like the camera preview to stay always in Landscape orientation and the overlay layout changing according to the device orientation.
I tried setting android:screenOrientation="landscape" in the manifest for the activity but then (of course) also the inflated layout stays always fixed, while not setting the android:screenOrientation property also the camera preview rotate, slowing down the app and showing strange form factors of the preview. Here the relevant code for the layout:
private void setupLayout()
{
setContentView(R.layout.main);
getWindow().setFormat(PixelFormat.UNKNOWN);
// Release camera if owned by someone else
if (camera != null)
releaseCamera();
surfaceView = (SurfaceView) findViewById(R.id.camerapreview);
surfaceHolder = surfaceView.getHolder();
surfaceHolder.addCallback(this);
surfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
controlInflater = LayoutInflater.from(getBaseContext());
View viewControl = controlInflater.inflate(R.layout.control, null);
LayoutParams layoutParamsControl = new LayoutParams(
LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT);
this.addContentView(viewControl, layoutParamsControl);
buttonGetCollectingData = (Button) findViewById(R.id.getcolldata);
buttonGetCollectingData.setOnClickListener(new Button.OnClickListener()
{
public void onClick(View arg0)
{
...
}
});
btnBackHome = (Button) findViewById(R.id.btnBackHome);
btnBackHome.setOnClickListener(new Button.OnClickListener()
{
public void onClick(View arg0)
{
...
}
});
autoFitTextViewMainMsg = (AutoFitTextView) findViewById(R.id.autoFitTextViewMainMsg);
buttonTakePicture.setOnClickListener(new Button.OnClickListener()
{
public void onClick(View arg0)
{
...
}
});
}
Any idea on how to accomplish this would be really appreciated!
You can make use of custom orientation event listener to get the orientation and set your UI as according.
First, create a class CustomOrientationEventListener
public abstract class CustomOrientationEventListener extends OrientationEventListener {
private static final String TAG = "CustomOrientationEvent";
private int prevOrientation = OrientationEventListener.ORIENTATION_UNKNOWN;
private Context context;
private final int ROTATION_O = 1;
private final int ROTATION_90 = 2;
private final int ROTATION_180 = 3;
private final int ROTATION_270 = 4;
private int rotation = 0;
public CustomOrientationEventListener(Context context) {
super(context);
this.context = context;
}
#Override
public void onOrientationChanged(int orientation) {
if (android.provider.Settings.System.getInt(context.getContentResolver(), Settings.System.ACCELEROMETER_ROTATION, 0) == 0) // 0 = Auto Rotate Disabled
return;
int currentOrientation = OrientationEventListener.ORIENTATION_UNKNOWN;
if (orientation >= 340 || orientation < 20 && rotation != ROTATION_O) {
currentOrientation = Surface.ROTATION_0;
rotation = ROTATION_O;
} else if (orientation >= 70 && orientation < 110 && rotation != ROTATION_90) {
currentOrientation = Surface.ROTATION_90;
rotation = ROTATION_90;
} else if (orientation >= 160 && orientation < 200 && rotation != ROTATION_180) {
currentOrientation = Surface.ROTATION_180;
rotation = ROTATION_180;
} else if (orientation >= 250 && orientation < 290 && rotation != ROTATION_270) {
currentOrientation = Surface.ROTATION_270;
rotation = ROTATION_270;
}
if (prevOrientation != currentOrientation && orientation != OrientationEventListener.ORIENTATION_UNKNOWN) {
prevOrientation = currentOrientation;
if (currentOrientation != OrientationEventListener.ORIENTATION_UNKNOWN) {
onSimpleOrientationChanged(rotation);
}
}
}
public abstract void onSimpleOrientationChanged(int orientation);
}
Then add below line to the Android manifest under your activity tag
android:configChanges="orientation|keyboardHidden|screenSize"
Make sure that you do not add android:screenOrientation property in manifest for that activity.
Then use the CustomOrientationEventListener class inside onCreate of your camera activity
public class YourActivity extends AppCompatActivity {
private CustomOrientationEventListener customOrientationEventListener;
final int ROTATION_O = 1;
final int ROTATION_90 = 2;
final int ROTATION_180 = 3;
final int ROTATION_270 = 4;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
.....
customOrientationEventListener = new
CustomOrientationEventListener(getBaseContext()) {
#Override
public void onSimpleOrientationChanged(int orientation) {
switch(orientation){
case ROTATION_O:
//rotate as on portrait
yourButton.animate().rotation(0).setDuration(500).start();
break;
case ROTATION_90:
//rotate as left on top
yourButton.animate().rotation(-90).setDuration(500).start();
break;
case ROTATION_270:
//rotate as right on top
yourButton.animate().rotation(90).setDuration(500).start();
break;
case ROTATION_180:
//rotate as upside down
yourButton.animate().rotation(180).setDuration(500).start();
break;
}
}
};
}
#Override
protected void onResume() {
super.onResume();
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
customOrientationEventListener.enable();
}
#Override
protected void onPause() {
super.onPause();
customOrientationEventListener.disable();
}
#Override
protected void onDestroy() {
super.onDestroy();
customOrientationEventListener.disable();
}
}
I have set am activity to handle configuration changes and it works, meaning that onConfigurationChanged() is called when the orientation changes.
The activity has a button to explicitly change the orientation. When clicked, it called setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_SENSOR_PORTRAIT).
Then the orientation is irrevocably set and onConfigurationChanged() is not called anymore.
How can I change the orientation when the user clicks the button while not loosing the onConfigurationChanged() callback ?
This is how I solved it. I am aware it is reinventing the wheel but it meets my requirement and I did not find a proper way to handle this with standard sdk tools.
First, create an OrientationManager class that listen to orientation changes
public class OrientationManager extends OrientationEventListener{
private static final String TAG = OrientationManager.class.getName();
private int previousAngle;
private int previousOrientation;
private Context context;
private OrientationChangeListener orientationChangeListener;
private static OrientationManager instance;
private OrientationManager(Context context) {
super(context);
this.context = context;
}
public static OrientationManager getInstance(Context context){
if (instance == null){
instance = new OrientationManager(context);
}
return instance;
}
public int getOrientation(){
return previousOrientation;
}
public void setOrientation(int orientation){
this.previousOrientation = orientation;
}
#Override
public void onOrientationChanged(int orientation) {
if (orientation == -1)
return;
if(previousOrientation == 0){
previousOrientation = context.getResources().getConfiguration().orientation;
if (orientationChangeListener != null){
orientationChangeListener.onOrientationChanged(previousOrientation);
}
}
if (previousOrientation == Configuration.ORIENTATION_LANDSCAPE &&
((previousAngle > 10 && orientation <= 10) ||
(previousAngle < 350 && previousAngle > 270 && orientation >= 350)) ){
if (orientationChangeListener != null){
orientationChangeListener.onOrientationChanged(Configuration.ORIENTATION_PORTRAIT);
}
previousOrientation = Configuration.ORIENTATION_PORTRAIT;
}
if (previousOrientation == Configuration.ORIENTATION_PORTRAIT &&
((previousAngle <90 && orientation >= 90 && orientation <270) ||
(previousAngle > 280 && orientation <= 280 && orientation > 180)) ){
if (orientationChangeListener != null){
orientationChangeListener.onOrientationChanged(Configuration.ORIENTATION_LANDSCAPE);
}
previousOrientation = Configuration.ORIENTATION_LANDSCAPE;
}
previousAngle = orientation;
}
public void setOrientationChangedListener(OrientationChangeListener l){
this.orientationChangeListener = l;
}
public interface OrientationChangeListener{
public void onOrientationChanged(int newOrientation);
}
}
Then in your activity implement OrientationChangeListener and override onOrientationChanged():
public class MyActivity extends Activity implements OrientationChangeListener{
private OrientationManager orientationManager;
#Override
public void onCreate(Bundle b){
orientationManager = OrientationManager.getInstance(this);
orientationManager.setOrientationChangedListener(this);
}
#Override
public void onOrientationChanged(int newOrientation) {
orientation = newOrientation;
if (newOrientation == Configuration.ORIENTATION_LANDSCAPE){
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_SENSOR_LANDSCAPE);
setLandscapeConfig();
}else{
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
setPortraitConfig();
}
}
So I don't use onConfigurationChanged anymore but keep the following line in the Manifest:
android:configChanges="orientation|screenSize"
Calling setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_SENSOR); will reactivate onConfigurationChanged. You can set up a timer like this:
// Force orientation to portrait
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_SENSOR_PORTRAIT);
// Reactivate sensor orientation after delay
Timer mRestoreOrientation = new Timer();
mRestoreOrientation.schedule(new TimerTask() {
#Override
public void run() {
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_SENSOR);
}
}, 2000);
We can only suppose the user will turn the device by himself to the forced orientation within the delay, and this can lead to bad user experience.
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_SENSOR_PORTRAIT)
This makes your onConfigurationChanged to stop working. If you want it to work, try adding this to your manifest within that activity:
android:configChanges="orientation|screenSize"
The screenSize attribute is only for API 13+ so if your below that, you don't need it
..after many search this the right code mix that solve. enjoy!
#Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
OrientationEventListener orientationEventListener = new
OrientationEventListener(getApplicationContext()) {
#Override
public void onOrientationChanged(int orientation) {
boolean isPortrait = isPortrait(orientation);
if (!isPortrait && savedOrientation == ActivityInfo.SCREEN_ORIENTATION_PORTRAIT) {
savedOrientation = ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE;
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_USER);
} else if (isPortrait && savedOrientation == ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE) {
savedOrientation = ActivityInfo.SCREEN_ORIENTATION_PORTRAIT;
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_USER);
}
}
};
orientationEventListener.enable();
}
private int savedOrientation;
private boolean isPortrait(int orientation)
{
if (orientation < 45 || orientation > 315) {
return true;
}
return false;
}
#Override
public void onConfigurationChanged(Configuration newConfig)
{
super.onConfigurationChanged(newConfig);
if(newConfig.orientation==Configuration.ORIENTATION_LANDSCAPE)
{
currentOrientation = ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE;
// do what you need in landscape mode....
}
else if(newConfig.orientation==Configuration.ORIENTATION_PORTRAIT)
{
currentOrientation = ActivityInfo.SCREEN_ORIENTATION_PORTRAIT;
// do what you need in portrait mode....
}
}
public void rotateScreenByUIButton() {
if (currentOrientation == ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE)
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
else
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
}
You just need to make the orientation back to SCREEN_ORIENTATION_UNSPECIFIED, the the onConfiguration change will be called again
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_SENSOR_LANDSCAPE)
->
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED)