Add click function on imagebutton dynamically using View.OnClickListener();
Onclicklistene() method is very important for image buttons because without use of onclicklistener() app developer cannot set click function on ImageButton. So here is the complete step by step tutorial for Set onclicklistener on ImageButton in android programmatically example.
Note: Please upload imagebutton image inside drawable-hdpi folder.
Download sample imagebutton from below and put it into drawable-hdpi folder.
How to Set onclicklistener on ImageButton in android programmatically example.
Code for MainActivity.java file.
package com.imagebuttonclick_android_examples.com; import android.app.Activity; import android.os.Bundle; import android.view.View; import android.widget.ImageButton; import android.widget.Toast; public class MainActivity extends Activity { ImageButton ClickImageButton; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); ClickImageButton = (ImageButton)findViewById(R.id.imageButton1); //Setting up on click event function on image button. ClickImageButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Toast.makeText(MainActivity.this, "Onclicklistener function called.", Toast.LENGTH_LONG).show(); } }); } }
Code for activity_main.xml layout file.
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:paddingBottom="@dimen/activity_vertical_margin" android:paddingLeft="@dimen/activity_horizontal_margin" android:paddingRight="@dimen/activity_horizontal_margin" android:paddingTop="@dimen/activity_vertical_margin" tools:context="com.imagebuttonclick_android_examples.com.MainActivity" > <ImageButton android:id="@+id/imageButton1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerHorizontal="true" android:layout_centerVertical="true" android:src="@drawable/image_button_click" /> </RelativeLayout>
Screenshot: