How to set Genaral onCLick for Views in XML layout in android?

Alireza Bideli :

My application have 17 ImageButtons which each of them has an animal image and if user clicks on it .That animal voice played for user.

As I said I have 17 ImageButtons .if I want to set OnClickListener for each of them .I have to write button.setOnCLickListenr(/*implementation*/); or button.setOnCLickListenr(this);* (within implementing View.OnCLickLIstener interface) 17 times .

My buttons are not near to themselves and so I can not use RecyclerView, ListView or GridLayout.

Is there any way to decrease the number of OnClickListener from 17 times to lower. or just use setOnClickListener method once

Thanks...

Ahmad :

Follow these steps this will helps you.

First: Define android:onClick="animalOnCLick" for each of your ImageButtons . This attributes make android to execute specific public method (!!!notice: your method should be public) when onCLick event happens in user device.

Layout Implementation

   <ImageButton
        android:id="@+id/btn_cow"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Cow"
        android:onClick="animalOnCLick" <!-- Added -->
        <!-- rest of imageButton attributes
        />
      <!-- other ImageButtons-->

Second : Declare a public method with the same name you have set in front of andorid:OnClick attribute and pass an argument which is type of View

public void animalOnCLick(View view) {
    /* your implementation*/
}

Third : Then get Current clicked View Id which is actually the current ImageButton clicked Id with view.getId()

And implement your unique implementation for each of your ImageButtons as below

    public void animalOnCLick(View view) {
      switch (view.getId())
      {
          case R.id.btn_cow:
              /*Cow onCLick implementation*/
              break;
          case R.id.btn_goat:
              /*Goat onCLick implementation*/
              break;
      /*Other ImageButtons      
    }
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=306038&siteId=1