How set the onClick event in a ImageButton?

rajeev patidar picture rajeev patidar · Mar 16, 2015 · Viewed 45.5k times · Source

I have created one image button in android, but when I am clicking on that button nothing is happening. I have set all the properties but still nothing is happening. So can you help me that where I am wrong.

xml file

    <?xml version="1.0" encoding="utf-8"?>
    <AbsoluteLayout
        android:id="@+id/widget39"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        xmlns:android="http://schemas.android.com/apk/res/android">

    <EditText
        android:id="@+id/editText1"
        android:layout_width="fill_parent"
        android:layout_height="50dp"
        android:layout_x="0dp"
        android:layout_y="3dp" />

    <ImageButton
        android:id="@+id/search"
        android:layout_width="40dp"
        android:layout_height="41dp"
        android:layout_x="312dp"
        android:layout_y="10dp"
        android:clickable="true"
        android:onClick="onClick"
        android:background="@drawable/search" />

    />
    </AbsoluteLayout>

search.java

public class SearchData extends Activity {
ImageButton search; 

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_search_data);
        search =(ImageButton)findViewById(R.id.search);
        search.setOnClickListener(new View.OnClickListener()   {             
               public void onClick(View v)  {               
                try {
                    ConnectService();
                } catch (Exception e) {
                    e.printStackTrace();                    
                }               
               }  
             });
    }

Answer

learner picture learner · Mar 16, 2015
<ImageButton
        android:id="@+id/search"
        android:layout_width="40dp"
        android:layout_height="41dp"
        android:layout_x="312dp"
        android:layout_y="10dp"
        android:clickable="true"
        android:onClick="onClick"
        android:background="@drawable/search" />

As per your xml you should remove android:onClick="onClick" line from your Image button Xml.Then it will work because 1st priority will go for always onClick method what you mentioned in xml.