我曾使用过TranslateAnimation
并在视图中向上和向下滑动。
然而,我意识到,即使在我向下滑动视图并在其可见性中使用View.GONE
之后,该视图仍然能够接收触摸事件。
通过单击按钮可以产生同样的问题,使橙色视图从屏幕底部消失。然后,当您单击屏幕底部时,您将意识到自定义视图的触摸事件仍在被触发。
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
int color = getResources().getColor(android.R.color.holo_orange_light);
// construct the RelativeLayout
final RelativeLayout customView = new RelativeLayout(this) {
@Override
public boolean onTouchEvent(MotionEvent event) {
this.setPressed(true);
Log.i("CHEOK", "OH NO! TOUCH!!!!");
return super.onTouchEvent(event);
}
};
customView.setBackgroundColor(color);
final FrameLayout frameLayout = (FrameLayout)this.findViewById(R.id.frameLayout);
frameLayout.addView(customView, new FrameLayout.LayoutParams(FrameLayout.LayoutParams.MATCH_PARENT, 100, Gravity.BOTTOM));
customView.setVisibility(View.GONE);
Button button = (Button)this.findViewById(R.id.button1);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (customView.getVisibility() != View.VISIBLE) {
// Slide up!
TranslateAnimation anim=new TranslateAnimation(0,0,100,0);
anim.setFillAfter(true);
anim.setDuration(200);
Log.i("CHEOK", "VISIBLE!!!");
customView.setVisibility(View.VISIBLE);
customView.setAnimation(anim);
customView.setEnabled(true);
} else {
// Slide down!
TranslateAnimation anim=new TranslateAnimation(0,0,0,100);
anim.setFillAfter(true);
anim.setDuration(200);
// HELPME : Not sure why, after I hide the view by sliding it down,
// making it View.GONE and setEnabled(false), it still able to
// receive touch event.
Log.i("CHEOK", "GONE!!!");
customView.setVisibility(View.GONE);
customView.setAnimation(anim);
customView.setEnabled(false);
}
}
});
}
}
可以在此处找到演示此问题的完整源代码:
https://www.dropbox.com/s/1101dm885fn5hzq/animator_bug.zip
如何将我的自定义视图设置为在我将其滑下后不接收触摸事件?
答案 0 :(得分:5)
我不清楚为什么您使用setAnimation()
代替startAnimation()
,因为您似乎没有为动画设置开始时间。
另一方面,我发现在有关联动画的情况下将视图设置为GONE并不会使其真正“GONE”。相反,您必须首先使用clearAnimation()
删除动画。
所以,改为:
public void onClick(View v) {
if (customView.getVisibility() != View.VISIBLE) {
// Slide up!
TranslateAnimation anim=new TranslateAnimation(0,0,100,0);
anim.setFillAfter(true);
anim.setDuration(200);
customView.setVisibility(View.VISIBLE);
customView.setEnabled(true);
customView.startAnimation(anim);
} else {
// Slide down!
TranslateAnimation anim=new TranslateAnimation(0,0,0,100);
anim.setFillAfter(true);
anim.setDuration(200);
anim.setAnimationListener(new AnimationListener() {
@Override
public void onAnimationEnd(Animation animation) {
customView.clearAnimation();
customView.setVisibility(View.GONE);
customView.setEnabled(false);
}
@Override
public void onAnimationRepeat(Animation animation) {
// nothing to do
}
@Override
public void onAnimationStart(Animation animation) {
// nothing to do
}
}
}
}
我不记得了,但您可能必须post()
onAnimationEnd()
的内容,而不是立即运行代码才能使其正常生效。