2

Below code is to create imageviews dynamically and add to its parent layout on click of a button. This works well. When i change the device orientation, everything is vanishing. i.e, After adding images if i change the device orientation the added images are missing. Why? How can i get back my images after changing the device orientation also?

 @Override
public void onClick(View v) {
    //create an imageview
    ImageView img = new ImageView(getApplicationContext());

    //set layout parameters
    img.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT)); 

    //set image source
    img.setImageResource(R.drawable.back);

    //add imageview to parent layout
    parentView.addView(img);        

}
user1129655
  • 55
  • 1
  • 6

2 Answers2

1

You can hanlde it by thises ways

1 - onSaveInstanceState() callback

ex: Saving Android Activity state using Save Instance State http://android-er.blogspot.in/2011/09/onsaveinstancestate-and.html

2- onRetainNonConfigurationInstance() with getLastNonConfigurationInstance()

ex: getLastNonConfigurationInstance()

3 - android:configChanges in menifest and orverirding onConfigChange in acivity ex:http://developer.android.com/resources/articles/faster-screen-orientation-change.html Activity restart on rotation Android

http://developer.android.com/guide/topics/resources/runtime-changes.html

choose one way as per your need...

Community
  • 1
  • 1
Dheeresh Singh
  • 15,446
  • 3
  • 35
  • 36
  • as per above description if image is need to restore then 2 option looks sufficient just get getLastNonConfigurationInstance() in onCreate, but not forgot null check. – Dheeresh Singh May 25 '12 at 05:22
  • http://blog.andresteingress.com/2011/09/27/fighting-orientation-changes-in-android/ – Dheeresh Singh May 25 '12 at 05:24
0

If you don't want to affect the Layout then just add this tag to you xml file.

android:configChanges="orientation|keyboardHidden"

This will help in changing your layout but wont affect anyother thing.

  <activity
        android:label="@string/app_name"
        android:name=".YourActivity" android:configChanges="orientation|keyboardHidden"/>
Bhavin
  • 5,572
  • 4
  • 21
  • 26