1

I created an image button that will change to another image when pressed. But, when I pressed the back button or switch to landscape orientation, the image button will go back to its default image.

I reckon that i need to save the image's state when it is pressed?

Anyone can help?

ib1.setOnClickListener(new View.OnClickListener() {
    public void onClick(View v) {
        if(isPressed)
            ib1.setBackgroundResource(R.drawable.star_pressed);

        else
            ib1.setBackgroundResource(R.drawable.star_unpressed);
            isPressed = true;
    }
});
Amit Vaghela
  • 22,772
  • 22
  • 86
  • 142
phosporus
  • 23
  • 6
  • You can save the state to SharedPreferences, then on the onResume method, you can load in the state and set the background – Thomas Jul 30 '16 at 05:22
  • Possible duplicate of [Android: Using selector to set background color for image view](http://stackoverflow.com/questions/8800343/android-using-selector-to-set-background-color-for-image-view) – Vishal Patoliya ツ Jul 30 '16 at 05:23
  • To preserve the state, it would be better to use the solution suggested by @Thomas. The "isPressed" flag could be used to decide the state in "onResume", and a background image be set accordingly – Nakul Sudhakar Jul 30 '16 at 05:27

3 Answers3

0

Do this for orientation changes

  <activity android:name=".Youractivity"

        android:configChanges="orientation|keyboard|keyboardHidden|screenSize"
    >

    </activity>
Arjun saini
  • 4,223
  • 3
  • 23
  • 51
0

Add bellow code in your manifest file

<activity
      android:name="YourActivity"
      android:configChanges="orientation|screenSize|keyboardHidden"
      android:theme="@style/AppTheme.NoActionBar" //if you need
      android:windowSoftInputMode="stateHidden" //if you need
 />
0

You can put button state in sharedpreferences and get button state in onResume method of activity.