I'm working on an android app, right now I limited the user to only use horizontal view for all activities.
I want to be able to give the user the option to rotate the screen, but when I do that, the activity starts from the beginning instead of just staying the same.
Any idea how to save the state when rotating the screen?
Firstly, you have to override onConfigurationChanged(Configuration) within your Activity.
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
// Checks the orientation of the screen
if (newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE) {
Toast.makeText(this, "landscape", Toast.LENGTH_SHORT).show();
} else if (newConfig.orientation == Configuration.ORIENTATION_PORTRAIT){
Toast.makeText(this, "portrait", Toast.LENGTH_SHORT).show();
}
}
You also have to edit the appropriate element in your manifest file to include the android:configChanges Just see the code below:
<activity android:name=".MyActivity"
android:configChanges="orientation|keyboardHidden"
android:label="#string/app_name">
I also like Marko's idea but it's simply not efficient. This way, we don't have to call onCreate/onStartup/etc. all the time we do a simple rotate. There is no need to "rebuild" the infrastructure from scratch (e.g. getting Views,..)
Each time you rotate the device, onCreate method is being called again. You can save the values by overriding onSavedInstanceState and get them back in onRestoreInstanceState or in onCreate method. For example lets save boolean(you can save whatever you want):
save the value:
public void onSaveInstanceState(Bundle outState) {
outState.putBoolean("booleanValue", true);
}
restore the value (you can call this in onCreate as well):
protected void onRestoreInstanceState(Bundle savedInstanceState) {
if (savedInstanceState != null && savedInstanceState.containsKey("booleanValue")) {
boolean myBoolean = savedInstanceState.getBoolean("booleanValue");
}
super.onRestoreInstanceState(savedInstanceState);
}
<activity (...)
android:configChanges="orientation|keyboard"
(...)>
Adding this to your manifest does not allow Android to restart the activity after chaging the layout.
Related
I want to set a autoplay sound and it only play once, no matter the rotation is. I was trying to make my Mediaplayer in the onCreate of Mainactivity. And when I try to rotate the screen, the audio continued to play.
I try a different method like set up a subclass and call in the activity instead of puting it in onCreat of MainActivity to make it only play once and ignore doing rotate, but it still doesn't work, can someone explain to me how can I fix it? Thank you!
You should use onConfigurationChanged to make this work.
in your manifest file add this to your activiy
android:configChanges="orientation|keyboardHidden"
<activity android:name=".MyActivity"
android:configChanges="orientation|keyboardHidden"
android:exported="true">
In your MainActiviy code implement this method:
#Override
public void onConfigurationChanged(#NotNull Configuration newConfig) {
super.onConfigurationChanged(newConfig);
// check weather the player is null
if(player == null) return;
player.stop();
}
You should clerify your case with code, but seams that it should help
#Override
protected void onStop() {
super.onStop();
player.release();
player = null;
}
I'm new to android development and have been making simple apps and in all of them have been making a method called void logic() that I have called at the end of my ViewDidLoad method. logic() contains all of the functionality that my app has. The issue with this is that whenever the screen changes orientation the ViewDidLoad method is re-called and then my app starts as if the application is being opened for the first time. Does anyone know how to do this? This is similar to this question Don't reload application when orientation changes however I do want ViewDidLoad to be re-called when the orientation is changed so that the view is recreated with the new orientation. However I don't want the application to be restarted. Thanks.
You can use :
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
// Checks the orientation of the screen
if (newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE) {
Toast.makeText(this, "landscape", Toast.LENGTH_SHORT).show();
} else if (newConfig.orientation == Configuration.ORIENTATION_PORTRAIT){
Toast.makeText(this, "portrait", Toast.LENGTH_SHORT).show();
}
}
or
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
}
And your activity manifest :
<activity android:name=".yourname"
android:configChanges="orientation|keyboardHidden">
</activity>
Based on the accepted answer here, I added this code to an Activity as what I hoped to be the first step in changing the assigned Layout for an Activity:
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
// Checks the orientation of the screen
if (newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE) {
Toast.makeText(this, "landscape", Toast.LENGTH_SHORT).show();
setContentView(R.layout.activity_settings_landscape);
} else if (newConfig.orientation == Configuration.ORIENTATION_PORTRAIT){
Toast.makeText(this, "portrait", Toast.LENGTH_SHORT).show();
setContentView(R.layout.activity_settings);
}
}
...and modified the Activity's element in AndroidManifest.xml. e.g., changing it from this:
<activity
android:name="hhs.app.SettingsActivity"
android:label="#string/title_activity_settings" >
</activity>
...becomes this:
<activity
android:name="hhs.app.SettingsActivity"
android:configChanges="orientation|keyboardHidden"
android:label="#string/title_activity_settings" >
</activity>
(I added the "configChanges" jazz).
But, although mashing keypad.9 does indeed flip the orientation in the emulator, no toast is being raised (the breakpoint on the "if" line of onConfigurationChanged() is not being hit). What am I doing wrong or omitting?
Note: It made no difference when I removed "|keyboardHidden" from the "configChanges" line in AndroidManifest (it was just a hunch - I wondered if it meant "pay no attention to an orientation change made via the keyboard").
UPDATE
I tried araut's suggestion, and also the one from Jared Burrows here, but neither one works for me.
Cold this be simply an emulator problem? I have no device to test it with yet, so I can't empirically answer that question myself.
UPDATE 2
Based on what I read here, I thought maybe adding some OrientationEventListener jazz would solve this dilemma, but no!
This is the code I added (shown in context; what's new is the OrientationEventListener stuff):
public class SettingsActivity extends ActionBarActivity {
private OrientationEventListener mOrientationListener;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_settings);
. . .
mOrientationListener = new OrientationEventListener(getApplicationContext()) {
#Override
public void onOrientationChanged(int orientation) {
Toast tostadaOrient = Toast.makeText(SettingsActivity.this,
orientation, Toast.LENGTH_SHORT);
tostadaOrient.setGravity(Gravity.CENTER, 0, 0);
tostadaOrient.show();
}
};
mOrientationListener.enable();
}
...but I still get no reaction (no toasts are raised from here or the onConfigurationChanged() event).
I'm trying to handle screen orientation change for my android application but without success.
Here's my manifest :
<activity
android:name="fr.ups.l3info.l3info_catchgameactivity.CatchGameActivity"
android:label="#string/app_name"
android:screenOrientation="user"
android:configChanges="orientation|keyboardHidden" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
and I adde this function in my activity class :
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
}
But when I change the screen orientation the application is recreated and this function is never executed. What I have done wrong? Thanks for your help.
Use this in your manifest
android:configChanges="keyboardHidden|orientation|screenSize|layoutDirection"
You might want to read more about activity lifecycle. More you can find here (http://developer.android.com/training/basics/activity-lifecycle/index.html)
But more important is to get familiar with your activity state.
Method you are looking for is not onConfigurationChanged(Configuration newConfig), but onSaveInstanceState(Bundle savedInstanceState).
Now in your OnCreate() method you will need to check if there is some state already saved, and then recreate that situation.
There is a very good explanation on this link: Saving Android Activity state using Save Instance State
But basically what you need to do is this:
#Override
public void onSaveInstanceState(Bundle savedInstanceState) {
// Save the user's current game state
savedInstanceState.putInt(STATE_SCORE, mCurrentScore);
savedInstanceState.putInt(STATE_LEVEL, mCurrentLevel);
// Always call the superclass so it can save the view hierarchy state
super.onSaveInstanceState(savedInstanceState);
}
and then with that in mind:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState); // Always call the superclass first
// Check whether we're recreating a previously destroyed instance
if (savedInstanceState != null) {
// Restore value of members from saved state
mCurrentScore = savedInstanceState.getInt(STATE_SCORE);
mCurrentLevel = savedInstanceState.getInt(STATE_LEVEL);
} else {
// Probably initialize members with default values for a new instance
}
...
}
STATE_SCORE and STATE_LEVEL are some public static final String values that are used to somehow label your stuff you want to save.
For example, if you have EditText view, and you type something in, then rotate your screen, that value will be lost. But in your onSaveInstanceState() method you shall use that Bundle parameter and put value of your EditText view as a String.
With that saved, now you can get that value in your onCreate() method and set the value of your EditText view to it.
Hope this helps :)
If you're trying to define a "different layout" to your app when the orientation changes, just define a new layout give it the same name as your other layout and put it under res/layout-land.
So that when your application recreates itself and calls setContentView(layout_name) within the onCreate function it will call the under res/layout-land and not the one under res/layout .
I want my title bar to be hidden when I turn my device to landscape. I have seen the XML option to hide the title bar, and the following example of doing it programmatically:
//Remove title bar
this.requestWindowFeature(Window.FEATURE_NO_TITLE);
//Remove notification bar
this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
BUT, I am using configChanges parameter for orientation and screenSize, so my activity is not re-created again when it is orienting to landscape (I'm doing this for some reasons). So I cannot use the above methods as these calls need to be made before setContentView().
So any ideas? Thank you.
was searching for an answer, ended up here, put the pieces together and here they are:
if (getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE) {
getWindow().addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
}
else {
getWindow().clearFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
}
Assuming you have defined configChangesfor the Activity in the manifest then you can achieve your issue overriding onConfigurationChanged method:
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
if(newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE) {
getActionBar().hide();
} else {
getActionBar().show();
}
}
You will have to use getSupportActionBar() instead of getActionBar() if using the support library.
first check your device orientation by using following code
The current configuration, as used to determine which resources to retrieve etc, as available from the Resources' Configuration object as:
getResources().getConfiguration().orientation
Then do the necessary coding related to hide title bar and notification bar.
#Override
public void onConfigurationChanged(Configuration config) {
super.onConfigurationChanged(config);
if(config.orientation == Configuration.ORIENTATION_LANDSCAPE) {
getWindow().addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
getActionBar().hide();
} else {
getWindow().clearFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
getActionBar().show();
}
}
You can use this I have tried by my self.
In your "AndroidManifest.xml", in the activity tag you can specify "NoTitleBar" in the theme property so that it will always hide the title:
<activity
android:name="com.my_package.MyActivity"
android:theme="#android:style/Theme.NoTitleBar.Fullscreen"
android:configChanges="navigation|orientation|screenLayout|layoutDirection">