I am developing a simple game and in an activity I have 2 image buttons:

    <ImageButton
        android:id="@+id/btn1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:contentDescription="@string/desc"
        android:src="@drawable/img1"
        android:onClick="btn1_click" />

    <ImageButton
        android:id="@+id/btn2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:contentDescription="@string/desc"
        android:src="@drawable/img2"
        android:onClick="btn2_click" />

And I am showing some animations when buttons are clicked:

public void btn1_click(View v) {
    v.startAnimation(animLeftTranslate);
}
public void btn2_click(View v) {
    v.startAnimation(animRightTranslate);
}

Of course, only the clicked button is being animated but what I want to do is to show animation for both two buttons when one of them are clicked. How can I do this?

有帮助吗?

解决方案 2

You can accomplish this by your own approach i.e. using android:onClick attribute:

Assign one function to both ImageButton for example btns_clicked(). So add android:onClick='btns_clicked' to both your buttons. And in that function write:

public void btns_clicked(View v) {
    View btn1 = findViewById(R.id.btn1);
    View btn2 = findViewById(R.id.btn2);

    btn1.startAnimation(animLeftTranslate);
    btn2.startAnimation(animRightTranslate);
}

其他提示

Instead of using android:onClick, you can do it in java code:

    ImageButton btn1 = (ImageButton) findViewById(R.id.bt1);
    ImageButton btn2 = (ImageButton) findViewById(R.id.bt2);

    View.OnClickListener listener = new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            btn1.startAnimation(animRightTranslate);
            btn2.startAnimation(animRightTranslate);
        }
    };
    btn1.setOnClickListener(listener);
    btn2.setOnClickListener(listener);`

`

you can do this as describe below.

 <ImageButton
    android:id="@+id/btn1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:contentDescription="@string/desc"
    android:src="@drawable/img1"
    android:onClick="btn_click" />

<ImageButton
    android:id="@+id/btn2"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:contentDescription="@string/desc"
    android:src="@drawable/img2"
    android:onClick="btn_click" />

and in activity, you have to use

public void btn_click(View v) {
if(v.getId() == R.id.btn1)
    v.startAnimation(animLeftTranslate);
else if(v.getId() == R.id.btn2)
    v.startAnimation(animRightTranslate);
}
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top