4.1 来去电时更改归属地显示的位置
2019-04-13 13:34发布
生成海报
1.在手机离开屏幕时,记录view对象距离屏幕left和top的距离,将数据存入到sp存储器中
2.在activity加载的时候获取存在sp存储器中的值,确定view对象的位置
public class DragViewActivity extends Activity
{
private static final String TAG = "DragViewActivity";
private ImageView iv_dragview;
private WindowManager wm;
private SharedPreferences sp;
private TextView tv_dragview;
@Override
protected void onCreate(Bundle
savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout. activity_dragview);
sp=getSharedPreferences( "config", MODE_PRIVATE);
wm=(WindowManager)
getSystemService( WINDOW_SERVICE);
iv_dragview =
(ImageView) findViewById(R.id. iv_dragview);
tv_dragview =(TextView)
findViewById(R.id.tv_dragview);
//当activity加载时确定Toast的位置
int left= sp.getInt( "left",
0);
int top= sp.getInt( "top",
0);
Log. i(TAG, "left:" +left);
Log. i(TAG, "top:" +top);
LayoutParams params=(LayoutParams) iv_dragview.getLayoutParams(); //获取布局参数
params. leftMargin=left;
params. topMargin=top;
iv_dragview.setLayoutParams(params); //设置view的布局
//给imageview 设置触摸事件
iv_dragview.setOnTouchListener( new OnTouchListener()
{
int startX=0; //离屏幕左边距离
int startY=0;
//当触摸时
@Override
public boolean onTouch(View
v, MotionEvent event) {
switch (event.getAction())
{
case MotionEvent. ACTION_DOWN: //触摸到屏幕时
startX =
( int) event.getRawX();
startY =
( int) event.getRawY();
break;
case MotionEvent. ACTION_MOVE: //滑动时
int newX
= ( int) event.getRawX();
int newY
= ( int) event.getRawY();
int dx
= newX - startX; //变化的距离
int dy
= newY - startY;
int l
= iv_dragview.getLeft()+dx; //获取view对象移动后的位置
int r
= iv_dragview.getRight()+dx;
int t
= iv_dragview.getTop()+dy;
int b
= iv_dragview.getBottom()+dy;
//判断view对象是都超出屏幕
if(l<0||t<0||r> wm.getDefaultDisplay(). getWidth()||b> wm.getDefaultDisplay(). getHeight()-40){
break;
}
iv_dragview.layout(l,
t, r, b); //定位view对象位置
startX =
( int) event.getRawX(); //重新获取开始位置
startY =
( int) event.getRawY();
int tv_height
= tv_dragview.getBottom()- tv_dragview.getTop();
//归属地提示TextView位置变化效果
if (t
> wm.getDefaultDisplay(). getHeight() /
2) {
// imageview 在下方,
设置textview 在上方
tv_dragview.layout( tv_dragview.getLeft(),
0,
tv_dragview.getRight(),
tv_height);
} else {
// imageview 在上方,
设置textview 在下方
tv_dragview.layout( tv_dragview.getLeft(), wm
.getDefaultDisplay(). getHeight()
- 40
- tv_height, tv_dragview.getRight(), wm
.getDefaultDisplay(). getHeight() -
40);
}
break;
case MotionEvent. ACTION_UP: //离开屏幕时
//将view对象距离屏幕左边的距离和距离屏幕上边的距离记录到 sp存储器中
int left= iv_dragview.getLeft();
int top= iv_dragview.getTop();
Editor edit = sp.edit();
edit.putInt( "left",
left);
edit.putInt( "top",
top);
edit.commit();
break;
}
return true;
}
});
}
}
打开微信“扫一扫”,打开网页后点击屏幕右上角分享按钮