Search code examples
androidandroid-galleryandroid-imagebutton

Changing imagebutton image(from gallery) with longclick


I've searched the forums, but not have found any specific or understandable answers for my problem.

I'd like to change my Imagebutton image to a picture, selected from the gallery. Prefferrably the image should stay changed after closing the application.

My XML for the button is here:

<ImageButton
        android:id="@+id/eat"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_margin="10dp"
        android:adjustViewBounds="true"
        android:background="@drawable/eat"
        android:clickable="true"
        android:longClickable="true"
        android:scaleType="fitCenter" />

The java code for playing the sound is here with the OnClick method.

    ImageButton eat = (ImageButton) findViewById (R.id.eat);
    eat.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            mp1.start();
        }
    });

I would like to add the OnLongClick method here too, (since to OnClick is allready taken and the image replacing should be a little different), but havent found the right way. Can You please guide me a little bit?


Solution

  • You need to return true from image's onLongClickListener.

    Like this:

    eat.setOnLongClickListener(new OnLongClickListener() {
    
        @Override
        public boolean onLongClick(View v) {
            //do something
            return true;
        }
    
    });
    
    eat.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            mp1.start();
        }
    });
    

    This will not cause the image's onClickListener to be called as it means that the action has already been handled in longClickListener.