Reputation: 1045
See http://www.passsy.de/multitouch-for-all-views/#comment-47486 of which the most relevant code appears below.
If one "TestButton" which extends button is pressed, that view is passed to my "TestButton" code and I can animate that button/view. But I want to animate another view as well. How can I animate a different view from with the view I am creating here or how can I notify my activity to DO ACTION? This works on button touched:
startAnimation(animationstd);
but on another button:
useiv.startAnimation(animationstd);
causes a null pointer exception.
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);
}
}
Upvotes: 0
Views: 411
Reputation: 3223
You can't call findViewById
from inside TestButton
since you haven't passed to it a reference to the layout your button is located in. You must call findViewById()
outside the TestButton
class to find the button that must be animated and then pass that reference to it. Like this:
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);
}
}
Then in your onCreate()
method:
@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);
Upvotes: 1