Saturday, June 29, 2013

How to add common OnClick event for ImageView for every activity? - Android

If your layout contains one common header (with an ImageView) across multiple activities.. you may need to write an OnClick event for the imageView in every single activity..

Instead of writing the same code in every activity you can write a class the extends OnClickListener and the OnClick method like below,

public class ImageViewOnclickListener implements OnClickListener {
  private Context context;
  public ImageViewOnclickListener(Context context) {    this.context = context;
  }

  @Override
  public void onClick(View arg0) {
    Intent intent = new Intent(context, SomeActivity.class);
    context.startActivity(intent);
  }
}

In your activities:
protected void onCreate(...) {
  setContentView(...);
  ((ImageView) findViewById(R.id.mybutton)).setOnClickListener(new ImageViewOnclickListener(this));
}
Hope this helps :)

No comments:

Post a Comment