ViewPager滑动后,可移动的Imageview会回到初始化的位置
知乎看到的原文http://www.zhihu.com/question/37398770?sort=created
ViewPager滑动后,可移动的Imageview会回到初始化的位置?
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<android.support.v4.view.ViewPager
android:id="@+id/viewpager"
android:layout_width="match_parent"
android:layout_height="180dp" />
<ImageView
android:id="@+id/image"
android:layout_width="160dp"
android:layout_height="160dp"
android:layout_below="@id/viewpager"
android:layout_centerHorizontal="true"
android:src="@mipmap/a" />
</RelativeLayout>
我在代码中监听了imageview的ontouch事件,重写onTouch方法实现imageview的移动:
private View.OnTouchListener movingEventListener = new View.OnTouchListener() {
int lastX, lastY;
@Override
public boolean onTouch(View v, MotionEvent event) {
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
lastX = (int) event.getRawX();
lastY = (int) event.getRawY();
break;
case MotionEvent.ACTION_MOVE:
int dx = (int) event.getRawX() - lastX;
int dy = (int) event.getRawY() - lastY;
int left = v.getLeft() + dx;
int top = v.getTop() + dy;
int right = v.getRight() + dx;
int bottom = v.getBottom() + dy;
// 设置不能出界
if (left < 0) {
left = 0;
right = left + v.getWidth();
}
if (right > screenWidth) {
right = screenWidth;
left = right - v.getWidth();
}
if (top < 0) {
top = 0;
bottom = top + v.getHeight();
}
if (bottom > screenHeight) {
bottom = screenHeight;
top = bottom - v.getHeight();
}
v.layout(left, top, right, bottom);
lastX = (int) event.getRawX();
lastY = (int) event.getRawY();
break;
case MotionEvent.ACTION_UP:
/* int flag = 0;
switch (v.getId()) {
}*/
}
return true;
}
};
运行程序后,imageview可以移动,但是移动之后,滑动ViewPager的话,ImageView就会回到最初的位置,请问一下这是为什么呢?
作者:陈宇轩
链接:http://www.zhihu.com/question/37398770/answer/88058631
来源:知乎
著作权归作者所有,转载请联系作者获得授权。
链接:http://www.zhihu.com/question/37398770/answer/88058631
来源:知乎
著作权归作者所有,转载请联系作者获得授权。
package fmy.qf.com.mancheng.customview; import android.content.Context; import android.util.AttributeSet; /** * Created by Administrator on 2016/10/10. */ public class MygifView extends pl.droidsonroids.gif.GifImageView { private boolean keepPosition; public MygifView(Context context) { super(context); } public MygifView(Context context, AttributeSet attrs) { super(context, attrs); } public MygifView(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); } @Override public void layout(int l, int t, int r, int b) { if (!keepPosition) { super.layout(l, t, r, b); keepPosition=true; } } public void moveTiger(int l, int t, int r, int b) { super.layout(l, t, r, b); } public void startKeepPosition() { keepPosition = true; } }