0

I have an ImageView on an Activity A, and a button on Activity B. The ImageView is set to "invisible". I was wondering if i could make the ImageView visible when the button is pressed and keep visible forever (until the user uninstalls the app or resets it).

I found this piece of code that makes the ImageView turn visible:

example.setVisibility(View.VISIBLE);

i know i should use SharedPreferences to make it work, but i tried many times, without success.

Can somebody help me?

Thank you so much.

P.s. What i have to do is to create (or simply make visible) a tick so that the user knows which level he completed. If there's another way, and i know there is, let me know.

Giulio Tedesco
  • 179
  • 1
  • 3
  • 14

2 Answers2

1

It seems you have set the visibility of your ImageView in XML using

android:visibility="invisible"

Instead of that always set the visibility in code using something like -

SharedPreferences sharedPreferences;

public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    sharedPreferences = getSharedPreferences(getString(R.string.sp_key), 
            MODE_PRIVATE);
    ImageView example = (ImageView) findViewById(R.id.example_image);
    boolean visible = sharedPreferences.getBoolean(R.string.visible, false);

    if (visible) {
        example.setVisibility(View.VISIBLE);
    } else {
        example.setVisibility(View.INVISIBLE);
    }
}

Then where the user clicks on a checkbox or something to show they want to make your ImageView visible, save this to the SharedPreferences. Have a look at How to use SharedPreferences in Android to store, fetch and edit values for more details on SharedPreferences example.

Community
  • 1
  • 1
rnk
  • 2,394
  • 1
  • 19
  • 19
  • This works, but when i touch the Button (that should set the visibility to "visible", by your code) the activity crashes. The line that gives problem is this one: example.setVisibility(View.VISIBLE); that's awkward... – Giulio Tedesco Feb 16 '14 at 21:54
0

I solved. Rnk's method is the key. It returned error because i was using findViewById with an object from another Layout and it returned null point. So i imported the layout where the imageView is, and i solved. THANK YOU.

Giulio Tedesco
  • 179
  • 1
  • 3
  • 14