Search code examples
androidandroid-imageviewdevice-orientation

Dynamically added images are missing on device orientation in android?


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

}

Solution

  • 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"/>