android studio自定义滑动空间时,使用 ObjectAnimator.ofFloat滑动后,getRight()值不变
代码大概如下:
<FrameLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<Button
android:stateListAnimator="@null"
android:layout_gravity="right"
android:text="删除"
android:gravity="center"
android:id="@+id/delete"
android:layout_width="30dp"
android:layout_height="30dp"/>
<com.example.myapplication.TestView //自定义控件
android:background="@color/colorAccent"
android:layout_width="match_parent"
android:layout_height="30dp">
</com.example.myapplication.TestView>
</FrameLayout>
空间重写代码
public class TestView extends LinearLayout {
public TestView(Context context){
super(context);
}
public TestView(Context context, AttributeSet attrs){
super(context,attrs);
}
public TestView(Context context, AttributeSet attrs, int defStyleAttr){
super(context,attrs,defStyleAttr);
}
int lastX;
int lastY;
int offsetX;
int startX;
int startY;
int itemwidth;
int buttonWidth;
int flag=1;
ViewGroup viewGroup;
@Override
public boolean onTouchEvent(MotionEvent event) {
int x = (int) event.getX();
int y = (int) event.getY();
switch ( event.getAction()){
case MotionEvent.ACTION_DOWN:
Log.d("TestView", "ACTION_DOWN: ");
flag =1;
lastX=x;
lastY=y;
startX=getRight();
itemwidth=getWidth();
viewGroup=(ViewGroup) getParent();
buttonWidth=viewGroup.getChildAt(0).getWidth();
break;
case MotionEvent.ACTION_MOVE:
Log.d("TestView", "ACTION_MOVE: ");
offsetX=lastX-x;
if (offsetX>0)
{
layout((getLeft()-offsetX),getTop(),(getRight()-offsetX),getBottom());
}
break;
case MotionEvent.ACTION_UP:
Log.d("TestView", "ACTION_UP: ");
Log.d("TestView", "*****back star");
Log.d("TestView", "1*****getRight ="+String.valueOf(getRight())+"getLeft"+
String.valueOf(getLeft()));
ObjectAnimator.ofFloat(this,"translationX",0,
(itemwidth-getRight())).setDuration(300).start();
Log.d("TestView", "2*****getRight ="+String.valueOf(getRight())+"getLeft"+ String.valueOf(getLeft()));
break;
}
return true;
}
}
这个功能是让控件可以左滑,然后放手的时候动画的形式回到屏幕右边(x方向值为1440),拖动控件到x=1317,然后调用 ObjectAnimator.ofFloat,控件屏幕上显示回到右边了,但getRight()得到的数值和调用前得到的数值一样,为1317而不是1440,为什么会这样呢?
2019-07-09 12:41:46.123 11400-11400/com.example.myapplication D/TestView: 1*****getRight =1317getLeft-123
2019-07-09 12:41:46.124 11400-11400/com.example.myapplication D/TestView: 2*****getRight =1317getLeft-123