Avoid main or activity class restart:
public void onConfigurationChanged(Configuration newConfig)
{
super.onConfigurationChanged(newConfig);
View mainLayout = findViewById(R.id.main_layout); // getting the layout
// Checks the orientation of the screen
if (newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE)
{
mainLayout.setBackgroundResource(R.drawable.my_bg_land);
}
else if (newConfig.orientation == Configuration.ORIENTATION_PORTRAIT)
{
mainLayout.setBackgroundResource(R.drawable.my_bg);
}
}
Note:
Please note on above code we access layout by its id(main_layout). To use this we have note it on layout xml file(that is xml file for your specific activity which is under res/layout here:res/layout/activity_main.xml)
Reference:
To do this note go to bin/res/AndroidManifest.xml, and add the following line under any activity where you want disable activity class refresh when orientation change.
android:configChanges="orientation|screenSize"
Change background Image:
To do this go to src/com.example.<yourproject>/<yourclass>Activity.java, for example src/com.example.firstapp/MainActivity.java, and add following function.
{
super.onConfigurationChanged(newConfig);
View mainLayout = findViewById(R.id.main_layout); // getting the layout
// Checks the orientation of the screen
if (newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE)
{
mainLayout.setBackgroundResource(R.drawable.my_bg_land);
}
else if (newConfig.orientation == Configuration.ORIENTATION_PORTRAIT)
{
mainLayout.setBackgroundResource(R.drawable.my_bg);
}
}
Note:
Please note on above code we access layout by its id(main_layout). To use this we have note it on layout xml file(that is xml file for your specific activity which is under res/layout here:res/layout/activity_main.xml)
android:id
=
"@+id/main_layout"
Reference:
Changing background of a layout at run time - http://manijshrestha.wordpress.com/2011/04/05/android-sdk-changing-background-of-a-layout-at-run-time/
Detect orientation change - http://stackoverflow.com/questions/5726657/how-to-detect-orientation-change-in-layout-in-android
No comments:
Post a Comment