Search code examples
javaandroidimagebuttongesture

Change Imagebutton Image using onFling


I was just playing around with Android Studio, so I've just been hard-coding what changes I would like to see when a gesture is done. So I know that the button won't change from jabong to amazon.com (although a bit of help making that dynamic would be helpful too!).

But before that, what I was having trouble with was changing the ImageButton's image when doing the onFling action.

The original image is in the drawable folder, and so is the image I would like to change it to.

My code's below.

public class MainActivity extends ActionBarActivity implements GestureDetector.OnGestureListener {

private TextView expiry;
private EditText JabongImpact;
private GestureDetectorCompat gestureDetector;
private ImageButton offer_image;
private Button storebutton;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    JabongImpact = (EditText) findViewById(R.id.JabongImpact);
    expiry = (TextView) findViewById(R.id.expiry);
    offer_image = (ImageButton) findViewById(R.id.offer_image);
    this.gestureDetector = new GestureDetectorCompat(this, this);
    Button mybutton = (Button) findViewById(R.id.storebutton);

    mybutton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Uri uri = Uri.parse("http://www.jabong.com");
            Intent intent = new Intent(Intent.ACTION_VIEW, uri);
            startActivity(intent);
        }
    });
    offer_image.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Uri uri = Uri.parse("http://www.jabong.com");
            Intent intent = new Intent(Intent.ACTION_VIEW, uri);
            startActivity(intent);
        }

    });

}

@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
    JabongImpact.setText("Impact shop with Amazon today!");
    expiry.setText("expires: tomorrow!");
    storebutton.setText("AMAZON.IN");
    return true;
}

@Override
public boolean onTouchEvent(MotionEvent event) {
    this.gestureDetector.onTouchEvent(event);
    return super.onTouchEvent(event);
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.menu_main, menu);
    return true;
}

Solution

  • you can change image in this way

    offer_image.setImageResource(R.drawable.<your drawable image>);