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...
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
}
}
you can use Butterknife library, check example:
@OnClick({ R.id.button1, R.id.button2, R.id.button3 })
public void onClicked(View view) {
// do something
}
You can create one OnClickListener and set it to all your ImageViews.
Example:
public OnClickListener onClickListener {
@Override
public void onClick(View view){
// Identify every imageview by its id
}
}
imageview1.setOnClickListener(onClickListener)
imageview2.setOnClickListener(onClickListener)
imageview3.setOnClickListener(onClickListener)
You can try like this instead of creating an inner class in every onclick
@Override
public void onClick(View v) {
int i = v.getId();
switch (i){
case R.id.btn1 :
break;
case R.id.btn2 :
break;
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.