请参阅下面显示最相关代码的http://www.passsy.de/multitouch-for-all-views/#comment-47486。
如果按下一个扩展按钮的“TestButton”,该视图将传递给我的“TestButton”代码,我可以为该按钮/视图设置动画。但我也希望为另一个视图制作动画。如何使用我在此处创建的视图设置不同视图的动画,或者如何通知我的活动以执行操作? 这适用于触摸按钮:
startAnimation(animationstd);
但在另一个按钮上:
useiv.startAnimation(animationstd);
导致空指针异常。
CODE:
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);
}
}
答案 0 :(得分:1)
您无法从findViewById
内部呼叫TestButton
,因为您尚未向其传递对按钮所在布局的引用。您必须在findViewById()
之外调用TestButton
{1}}类来查找必须设置动画的按钮,然后将该引用传递给它。像这样:
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);