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)
Related
I'm building an app for video streaming. It has a layout Youtube-style, with a portrait layout showing the video on top and a list of other content on the bottom. The app can show the video fullscreen on landscape either by rotating the device, or by clicking a button.
Now, if I rotate the phone to landscape and then I rotate it back to portrait, the layout is going back to portrait as expected. If instead I click the button to force the portrait mode, rotate the device in landscape to see the video, and then I rotate it back to portrait, the layout remains stuck to landscape.
My activity in the manifest:
<activity
android:name="MyActivity"
android:configChanges="keyboardHidden|orientation|screenSize|smallestScreenSize|screenLayout"
android:label="#string/app_name"
android:launchMode="singleTask" />
My button click:
mChangeOrientButton.setOnClickListener((OnClickListener)(new OnClickListener() {
public final void onClick(View it) {
if (getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT) {
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
} else if(getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE){
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
} else {
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED);
}
}
}));
My onConfigurationChanged method (I noticed that if I click the button and then rotate the phone, this method is not called anymore, as long as the requestedOrientation remains set in something different than UNSPECIFIED):
#Override
public void onConfigurationChanged(Configuration newConfig)
{
super.onConfigurationChanged(newConfig);
if (newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE) {
{
// Set the layout for landscape mode
} else if (newConfig.orientation == Configuration.ORIENTATION_PORTRAIT){
// Set the layout for portrait mode
}
}
I tried to reset the requestedOrientation to UNSPECIFIED like this:
#Override
public void onConfigurationChanged(Configuration newConfig)
{
super.onConfigurationChanged(newConfig);
if (newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE) {
{
// Set the layout for landscape mode
} else if (newConfig.orientation == Configuration.ORIENTATION_PORTRAIT){
// Set the layout for portrait mode
}
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED);
}
but it doesn't work, because the orientation is forced from portrait to landscape and then set again to unspecified before the user has a chance to rotate it to landscape, so it immediately changes again to portrait and it seems that it's doing nothing.
Ok, I found a solution looking at this other answer. It was not working for me, so I modified it slightly:
MainActivity
import android.content.Context;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.Surface;
import android.widget.ImageView;
public class MainActivity extends AppCompatActivity {
private SensorManager mSensorManager;
private Sensor mOrientation;
private boolean mIsForcingOrientation = false;
float value_0 = -10000;
float value_1 = -10000;
private SensorEventListener mOrientationSensorListener = new SensorEventListener() {
int orientation = -1;
#Override
public void onSensorChanged(SensorEvent event) {
int value ;
if(value_0 == event.values[0] && value_1==event.values[1]){
return;
}
if (value_0 < 0 && event.values[0] > 0){
// Setting rotation to 270°: Landscape reverse
value = Surface.ROTATION_270;
} else if (value_0 > 0 && event.values[0] < 0){
// Setting rotation to 90°: Landscape
value = Surface.ROTATION_90;
} else if (value_1 < 0 && event.values[1] > 0){
// Setting rotation to 180°: Portrait reverse
value = Surface.ROTATION_180;
} else if (value_1 > 0 && event.values[1] < 0){
// Setting rotation to 0°: Portrait
value = Surface.ROTATION_0
} else {
value = orientation;
}
if (orientation != value) {
if((requestedOrientation == ActivityInfo.SCREEN_ORIENTATION_PORTRAIT && (value == Surface.ROTATION_90 || value == Surface.ROTATION_270) ) ||
(requestedOrientation == ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE && (value == Surface.ROTATION_0 || value == Surface.ROTATION_180) ) ){
isForcingOrientation = false;
requestedOrientation = ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED;
}
}
value_0=event.values[0];
value_1=event.values[1];
}
#Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Get sensor manager
mSensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
// Get the default sensor of specified type
mOrientation = mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
mChangeOrientButton.setOnClickListener((OnClickListener)(new OnClickListener() {
public final void onClick(View it) {
mIsForcingOrientation = true;
if (getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT) {
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
} else if(getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE){
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
} else {
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED);
}
}
}));
}
#Override
protected void onResume() {
super.onResume();
if (mOrientation != null) {
mSensorManager.registerListener(mOrientationSensorListener, mOrientation,
SensorManager.SENSOR_DELAY_GAME);
}
}
#Override
protected void onPause() {
super.onPause();
if (mOrientation != null) {
mSensorManager.unregisterListener(mOrientationSensorListener);
}
}
}
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.
I want to find the camera screen orientation in locked portrait orientation mode, well I am using camera in my fragment class and I have already set my screen orientation as portrait, but the problem I am facing is, when I turn my camera from portrait to landscape its getting changed and I need to set capture button visible only when the camera is in portrait mode. Can anyone help me to get the orientation changes in portrait mode?
Below is my code:
getActivity().setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
sensorManager.registerListener(new SensorEventListener() {
int orientation=-1;;
#Override
public void onSensorChanged(SensorEvent event) {
if (event.values[1] < 6.5 && event.values[1] > -6.5) {
if (orientation!=1) {
Log.d("Sensor", "Landscape");
}
orientation = 1;
} else {
if (orientation!=0) {
Log.d("Sensor", "Portrait");
}
orientation = 0;
}
}
#Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
}, sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER), SensorManager.SENSOR_DELAY_GAME);
if (orientation == 0) {
// capture button visisble
} else {
// invisible
}
You can use OrientationEventListener for this. this is class that customise it.
public abstract class SimpleOrientationListener extends OrientationEventListener {
public static final int CONFIGURATION_ORIENTATION_UNDEFINED = Configuration.ORIENTATION_UNDEFINED;
private volatile int defaultScreenOrientation = CONFIGURATION_ORIENTATION_UNDEFINED;
public int prevOrientation = OrientationEventListener.ORIENTATION_UNKNOWN;
private Context ctx;
private ReentrantLock lock = new ReentrantLock(true);
public SimpleOrientationListener(Context context) {
super(context);
ctx = context;
}
public SimpleOrientationListener(Context context, int rate) {
super(context, rate);
ctx = context;
}
#Override
public void onOrientationChanged(final int orientation) {
int currentOrientation = OrientationEventListener.ORIENTATION_UNKNOWN;
if (orientation >= 330 || orientation < 30) {
currentOrientation = Surface.ROTATION_0;
} else if (orientation >= 60 && orientation < 120) {
currentOrientation = Surface.ROTATION_90;
} else if (orientation >= 150 && orientation < 210) {
currentOrientation = Surface.ROTATION_180;
} else if (orientation >= 240 && orientation < 300) {
currentOrientation = Surface.ROTATION_270;
}
if (prevOrientation != currentOrientation && orientation != OrientationEventListener.ORIENTATION_UNKNOWN) {
prevOrientation = currentOrientation;
if (currentOrientation != OrientationEventListener.ORIENTATION_UNKNOWN)
reportOrientationChanged(currentOrientation);
}
}
private void reportOrientationChanged(final int currentOrientation) {
int defaultOrientation = getDeviceDefaultOrientation();
int orthogonalOrientation = defaultOrientation == Configuration.ORIENTATION_LANDSCAPE ? Configuration.ORIENTATION_PORTRAIT
: Configuration.ORIENTATION_LANDSCAPE;
int toReportOrientation;
if (currentOrientation == Surface.ROTATION_0 || currentOrientation == Surface.ROTATION_180)
toReportOrientation = defaultOrientation;
else
toReportOrientation = orthogonalOrientation;
onSimpleOrientationChanged(toReportOrientation);
}
/**
* Must determine what is default device orientation (some tablets can have default landscape). Must be initialized when device orientation is defined.
*
* #return value of {#link Configuration#ORIENTATION_LANDSCAPE} or {#link Configuration#ORIENTATION_PORTRAIT}
*/
private int getDeviceDefaultOrientation() {
if (defaultScreenOrientation == CONFIGURATION_ORIENTATION_UNDEFINED) {
lock.lock();
defaultScreenOrientation = initDeviceDefaultOrientation(ctx);
lock.unlock();
}
return defaultScreenOrientation;
}
/**
* Provides device default orientation
*
* #return value of {#link Configuration#ORIENTATION_LANDSCAPE} or {#link Configuration#ORIENTATION_PORTRAIT}
*/
private int initDeviceDefaultOrientation(Context context) {
WindowManager windowManager = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
Configuration config = context.getResources().getConfiguration();
int rotation = windowManager.getDefaultDisplay().getRotation();
boolean isLand = config.orientation == Configuration.ORIENTATION_LANDSCAPE;
boolean isDefaultAxis = rotation == Surface.ROTATION_0 || rotation == Surface.ROTATION_180;
int result = CONFIGURATION_ORIENTATION_UNDEFINED;
if ((isDefaultAxis && isLand) || (!isDefaultAxis && !isLand)) {
result = Configuration.ORIENTATION_LANDSCAPE;
} else {
result = Configuration.ORIENTATION_PORTRAIT;
}
return result;
}
/**
* Fires when orientation changes from landscape to portrait and vice versa.
*
* #param orientation value of {#link Configuration#ORIENTATION_LANDSCAPE} or {#link Configuration#ORIENTATION_PORTRAIT}
*/
public abstract void onSimpleOrientationChanged(int orientation);
}
Then where you want to detect orientation just call
SimpleOrientationListener mOrientationListener = new SimpleOrientationListener(
context) {
#Override
public void onSimpleOrientationChanged(int orientation) {
if(orientation == Configuration.ORIENTATION_LANDSCAPE){
}else if(orientation == Configuration.ORIENTATION_PORTRAIT){
}
}
};
mOrientationListener.enable();
You gonna have to use:
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
if (newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE) {
} else if (newConfig.orientation == Configuration.ORIENTATION_PORTRAIT){
//do your stuff with the button
}
}
If you want your activity not to be recreated during orientation then use
android:configChanges="orientation|keyboardHidden|screenSize"
If you want your activity to be forced to stay portrait then you gonna have to use
in your manifest file in the activity you would like just try android:screenOrientation="portrait"
Hope it helps!!!
You can achieve the orientation change value, when your activity set to only Portrait or Landscape specific and you want to perform some action when orientation changes.
private OrientationEventListener orientationEventListener;
initialize this variable in your class and implement it's listener in onCreate
orientationEventListener = new OrientationEventListener(this) {
#Override
public void onOrientationChanged(int orientation) {
Log.d("Orientation", orientation + " - " + currentOrientation);
if (orientation >= 330 || orientation < 30) {
currentOrientation = Surface.ROTATION_0;
} else if (orientation >= 60 && orientation < 120) {
currentOrientation = Surface.ROTATION_90;
} else if (orientation >= 150 && orientation < 210) {
currentOrientation = Surface.ROTATION_180;
} else if (orientation >= 240 && orientation < 300) {
currentOrientation = Surface.ROTATION_270;
}
}
};
currentOrentation is integer value for later use in the activity other units.
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();
}
}