Android: Rotate only overlay Buttons on camera preview - android

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();
}
}

Related

Rotate CustomView without affecting the activity

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.

Override onConfigurationChanged while maintaining portrait mode

How do I detect landscape mode while maintaining my layouts in portrait mode?
I have an activity which maintains the portrait mode irrespective of actual mobile orientation. I can do this by adding android:screenOrientation="portrait" to my activity configuration in manifest.
However, I want to detect screenOrientation while maintaining the activity in portrait.
I have tried with following code:
#Override
public void onConfigurationChanged(Configuration newConfig) {
if (newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE) {
recordConfigChanges(newConfig); // Performs some variable changes or similar
}
// Maintain activity in portrait mode itself
Configuration customConfig = newConfig;
customConfig.orientation = Configuration.ORIENTATION_PORTRAIT;
super.onConfigurationChanged(customConfig);
}
The above code does not maintain portrait, it rotates the UI to landscape mode.
Re-iterating the original question, how do I detect landscape mode while maintaining my layouts in portrait mode?
You can use CustomOrientationEventListener without affect actual Orientation change
in your activity
...
private CustomOrientationEventListener customOrientationEventListener;
...
customOrientationEventListener = new CustomOrientationEventListener(mContext) {
#Override
public void onSimpleOrientationChanged(int orientation) {
}
};
customOrientationEventListener.enable();
standalone class CustomOrientationEventListener
public abstract class CustomOrientationEventListener extends OrientationEventListener {
private String TAG="CustomOrientation";
private static final int CONFIGURATION_ORIENTATION_UNDEFINED = Configuration.ORIENTATION_UNDEFINED;
private volatile int defaultScreenOrientation = CONFIGURATION_ORIENTATION_UNDEFINED;
private int prevOrientation = OrientationEventListener.ORIENTATION_UNKNOWN;
private Context ctx;
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;
private ReentrantLock lock = new ReentrantLock(true);
public CustomOrientationEventListener(Context context) {
super(context);
ctx = context;
}
public CustomOrientationEventListener(Context context, int rate) {
super(context, rate);
ctx = context;
}
#Override
public void onOrientationChanged(final int orientation) {
//return if auto rotate disabled. should rotate if auto rotate enabled only
if (android.provider.Settings.System.getInt(ctx.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)
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);
}

How to detect my screen orientation in portrait locked screen in android?

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.

onConfigurationChanged not called once setRequestedConfiguration has been used

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)

Animations in Android

I'm new in Android and I want to do some animations. I'm trying to make my sprite sheet move automatically. But there is a problem with screen rendering. It leaves a trail while it is moving.Click here to see the screen shot
This is my code:
public class SampleAnimationActivity extends Activity {
/** Called when the activity is first created. */
Screen screen;
MapAnimation mapAnimation;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
screen = new Screen(this);
setContentView(screen);
}
#Override
protected void onDestroy() {
super.onDestroy();
}
#Override
protected void onPause() {
super.onPause();
}
#Override
protected void onResume() {
super.onResume();
}
public class Screen extends SurfaceView implements Callback{
private SurfaceHolder holder;
private MySurfaceViewThread mySurfaceViewThread;
private boolean isSurfaceCreated;
private Bitmap character, tiles;
public Screen(Context context) {
super(context);
initialize();
}
public void initialize(){
//Create a new SurfaceHolder and assign this class as its callback...
holder = getHolder();
holder.addCallback(this);
isSurfaceCreated = false;
character = BitmapFactory.decodeResource(getResources(),R.drawable.penguin_sprite);
tiles = BitmapFactory.decodeResource(getResources(), R.drawable.tile_sprites);
resume();
}
public void resume(){
//Create and start the graphics update thread.
if(mySurfaceViewThread == null){
mySurfaceViewThread = new MySurfaceViewThread();
if(isSurfaceCreated == true){
mySurfaceViewThread.start();
}
}
}
public void pause(){
//Kill the graphics update thread
if(mySurfaceViewThread != null){
mySurfaceViewThread.pause();
mySurfaceViewThread = null;
}
}
#Override
public void surfaceChanged(SurfaceHolder holder, int format, int width,
int height) {
}
#Override
public void surfaceCreated(SurfaceHolder holder) {
isSurfaceCreated = true;
if(mySurfaceViewThread != null){
mySurfaceViewThread.start();
}
}
#Override
public void surfaceDestroyed(SurfaceHolder holder) {
isSurfaceCreated = false;
pause();
}
public class MySurfaceViewThread extends Thread{
private boolean isPaused;
private boolean characterLoaded, characterDrawn;
private SurfaceHolder surfaceHolder;
public MySurfaceViewThread(){
super();
isPaused = false;
characterLoaded = false;
surfaceHolder = holder;
characterDrawn = false;
}
public void run(){
//Repeat the drawing loop until the thread is stopped
while(!isPaused){
if(!surfaceHolder.getSurface().isValid()){
continue;
}
if(characterLoaded == false){
mapAnimation = new MapAnimation(screen, character);
characterLoaded = true;
}
Canvas canvas = surfaceHolder.lockCanvas();
mapAnimation.onDraw(canvas);
surfaceHolder.unlockCanvasAndPost(canvas);
}
}
public void pause(){
}
public void onDraw(){
}
}
}
}
public class MapAnimation {
private Screen screen;
private Bitmap character;
private int width, height, xPosition, yPosition, xSpeed, ySpeed;
public MapAnimation(Screen screen, Bitmap character) {
this.screen = screen;
this.character = character;
this.width = character.getWidth();
this.height = character.getHeight();
xPosition = 0;
yPosition = 0;
xSpeed = 5;
ySpeed = 5;
}
public void updateCharacter(){
if(xPosition > screen.getWidth() - width - xSpeed){
xSpeed = 0;
ySpeed = 5;
}
if(yPosition > screen.getHeight() - height - ySpeed){
xSpeed = -5;
ySpeed = 0;
}
if(xPosition + xSpeed < 0){
xPosition=0;
xSpeed = 0;
ySpeed = -5;
}
if(yPosition+ySpeed < 0){
yPosition = 0;
xSpeed = 5;
ySpeed = 0;
}
xPosition += xSpeed;
yPosition += ySpeed;
}
public void onDraw(Canvas canvas){
updateCharacter();
Rect src = new Rect(0, 0,135,225);
Rect dst = new Rect(xPosition, yPosition, xPosition+width, yPosition+height);
canvas.drawBitmap(character, src, dst, null);
}
}
Your help will be deeply appreciated :)
I already solved my problem, I just need to add "drawColor(color.BLACk);" before calling mapAnimation.onDraw() method.

Categories

Resources