MainActivity 中通过Viewpager 管理了四个Fragment,需求是在第一个Fragment(HomeFragment)中放置
HomeFramgment中找到控件,这里是一个button,
保存拖动过程的位置,在addOnLayoutChangeListener中重写设置,点击事件:保存按下的系统时间和抬起时系统时间,多少时间内算是点击事件。
成员位置
privateButtonbtnPrivilege;
private int[][]btnPosition= {new int[4]};
Fragment的onCreatView()方法中,(可抽取出去)
//这里获取屏幕的宽高
Display display = getActivity().getWindowManager().getDefaultDisplay();
Point point =newPoint();
display.getSize(point);
final intscreenWidth = point.x;
final intscreenHeight = point.y;
// 拖动的按钮
btnfloat= view.findViewById(R.id.btn_float);
// 给button添加触摸事件
View.OnTouchListener btnNewerPrivilegeTouchListener =newView.OnTouchListener() {
intlastX,lastY;// 记录移动的最后的位置
long startTouch;
long endTouch;
public booleanonTouch(View v,MotionEvent event) {
// 获取Action
intea = event.getAction();
switch(ea) {
caseMotionEvent.ACTION_DOWN:// 按下
lastX= (int) event.getRawX();
lastY= (int) event.getRawY();
startTouch= System.currentTimeMillis();
break;
/**
* layout(l,t,r,b) l Left position, relative to parent t Top
* position, relative to parent r Right position, relative to
* parent b Bottom position, relative to parent
* */
case MotionEvent.ACTION_MOVE:// 移动
// 移动中动态设置位置
intdx = (int) event.getRawX() -lastX;
intdy = (int) event.getRawY() -lastY;
intleft = v.getLeft() + dx;
inttop = v.getTop() + dy;
intright = v.getRight() + dx;
intbottom = 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();
intleft1 = v.getLeft();
inttop1 = v.getTop();
btnPosition[0] =new int[]{left,top,right,bottom};
break;
caseMotionEvent.ACTION_UP:// 脱离
endTouch= System.currentTimeMillis();
if(endTouch-startTouch<=200) {
Intent intent =newIntent(getActivity(),BaseWebViewActivity.class);
intent.putExtra("url",NetConfig.HOME_NERNER_PRIVILEGE_URL);
startActivity(intent);
}
break;
}
return false;
}
};
btnfloat.setOnTouchListener(btnNewerPrivilegeTouchListener);
给button设置保存位置
view.addOnLayoutChangeListener((view1,i,i1,i2,i3,i4,i5,i6,i7) -> {
if(btnPosition[0][0] !=0) {
btnPrivilege.layout(btnPosition[0][0],btnPosition[0][1],btnPosition[0][2],btnPosition[0][3]);
}
});
网友评论