Tutorial :change image onConfigurationChanged



Question:

Is there a way to change ImageView drawable with its corresponding drawable for landscape mode without destroying the whole activity. I tried to set the drawable again in onConfigurationChanged callback but it doesn't work. Something like this

@Override  public void onConfigurationChanged(Configuration conf) {      super.onConfigurationChanged(conf);      mImageView.setImageDrawable(getResources().getDrawable(R.drawable.iv));  }  

When i star the activity in landscape mode to correct drawable is displayed so resources are located correctly.


Solution:1

In your sample project just replace

iv.setBackgroundResource(R.drawable.android);  

with

iv.setImageDrawable(getResources().getDrawable(R.drawable.android));  

I guess setBackgroundResource does nothing because the same resource is already assigned to ImageView.

Take a look at this
http://open-pim.com/tmp/ImageTest.zip
I tried your approach and it works just great for me.


Solution:2

Is there a way to change ImageView drawable with its corresponding drawable for landscape mode without destroying the whole activity.

When you change from portrait to landscape or vice versa the Activity is recreated. Check that the onCreate() method is called.

If you want to avoid this kind of behaviour use:

android:configChanges="orientation|keyboardHidden"  

for your Activity in the AndroidManifest.

--

In relation to your question: I first would check what it's called first after an orientation change: onConfigurationChanged or onCreate.

If onConfigurationChanged is called first, then your setContentView() in your onCreate() method is replacing your ImageView drawable.


Solution:3

For the emulator, you'll need screenLayout in addition to orientation to call the method.

android:configChanges="orientation|screenLayout"  

Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Previous
Next Post »