0

请参阅http://www.passsy.de/multitouch-for-all-views/#comment-47486,其中最相关的代码如下所示。

如果按下一个扩展按钮的“TestButton”,则该视图将传递给我的“TestButton”代码,我可以为该按钮/视图设置动画。但我也想为另一个视图设置动画。如何使用我在此处创建的视图为不同的视图设置动画,或者如何通知我的活动以执行操作?这适用于触摸的按钮:

startAnimation(animationstd);

但在另一个按钮上:

useiv.startAnimation(animationstd);

导致空指针异常。

代码:

package de.passsy.multitouch;

import android.content.Context;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.widget.Button;

public class TestButton extends Button {

public TestButton(final Context context, final AttributeSet attrs) {
    super(context, attrs);

}

@Override
public boolean onTouchEvent(final MotionEvent event) {

    if (event.getAction() == MotionEvent.ACTION_DOWN) {
            final Animation animationstd = AnimationUtils.loadAnimation(getContext(),
            R.anim.fromleft);
    useiv = (TestButton) findViewById(R.id.imageButton1); 
    useiv.startAnimation(animationstd); //this line = null pointer exception
    }
    return super.onTouchEvent(event);
}
}
4

1 回答 1

1

您不能findViewById从内部调用,TestButton因为您没有将对按钮所在布局的引用传递给它。您必须findViewById()在类外部调用TestButton以找到必须设置动画的按钮,然后将该引用传递给它。像这样:

public class TestButton extends Button {

    TestButton mImageButton; // You were calling it useiv

    public TestButton(final Context context, final AttributeSet attrs) {
        super(context, attrs);
    }

    public setAnotherButtonToAnimate(TestButton button) {
        this.mImageButton = button;
    }

    @Override
    public boolean onTouchEvent(final MotionEvent event) {

        if (event.getAction() == MotionEvent.ACTION_DOWN) {
            final Animation animationstd = AnimationUtils.loadAnimation(getContext(), R.anim.fromleft);
            if (mImageButton != null) {
                mImageButton.startAnimation(animationstd);
            }
        }
        return super.onTouchEvent(event);
    }
}

然后在你的onCreate()方法中:

@Override
public void onCreate(final Bundle savedInstanceState) {
    requestWindowFeature(Window.FEATURE_NO_TITLE);
    getWindow().addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
    getWindow().clearFlags(
            WindowManager.LayoutParams.FLAG_FORCE_NOT_FULLSCREEN);

    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    TestButton imageButton1 = (TestButton) findViewById(R.id.imageButton1);
    (...)
    btn4 = (TestButton) findViewById(R.id.button4);
    btn4.setAnotherButtonToAnimate(imageButton1);
    btn4.setOnTouchListener(this);
于 2013-06-11T12:09:08.110 回答