branch4 Blog

Internet development with every single possibility.

[Android] onClick Event With ImageView

| Comments

Purpose

As said in the title.
It was my first shot using onClick event with ImageView, so just for memo.
(in fact it’s my first Android development)
Keep in mind that this seem just to be one way of implementing onClick event with a view.

Details

Follow these 2steps
  1. set a function name that should be called on onClick event in XML file(say it’s onClickEvent in this entry)
  2. declare the onClickEvent in java file(Let’s say we just pop a toast)
This is part of the XML file.
    <ImageView
    android:id="@+id/imageview01"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:src="@drawable/image"
    android:layout_gravity="bottom"
    android:scaleType="fitEnd"
    android:onClick="onClickEvent" />***** <- this Line !!!!  
Now, declare onClickEvent in the activity.
I use SherlockActivity, and SlidingMenu so it’s a little messy, but it’s ok to remove those.

    public class MainActivity extends SherlockActivity {
      @Override
      protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setTheme(R.style.Theme_Sherlock);
        setTitle(R.string.attach);
        // set the content view
        setContentView(R.layout.activity_main);
        // configure the SlidingMenu
        SlidingMenu menu = new SlidingMenu(this);
        menu.setMode(SlidingMenu.LEFT);
        menu.setTouchModeAbove(SlidingMenu.TOUCHMODE_FULLSCREEN);
        menu.setShadowWidthRes(R.dimen.shadow_width);
        menu.setShadowDrawable(R.drawable.shadow);
        menu.setBehindOffsetRes(R.dimen.slidingmenu_offset);
        menu.setFadeDegree(0.35f);
        menu.attachToActivity(this, SlidingMenu.SLIDING_CONTENT);
        menu.setMenu(R.layout.list);
      }
      public void onClickEntry(View v) {
        Toast.makeText(MainActivity.this, "test", Toast.LENGTH_LONG).show();
      }
    }
And you should see the toast after the tap.

Comments