android 动态控制控件位置 控件位置为点击位置

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_38357358/article/details/84637149

需求:进度圈显示在手指点击位置
设备:平板
解决办法:将点击事件获取到的位置(MotionEvent e)与控件设置位置建立联系
在网上找了很多都没有解决问题,下面代码为自己摸索得到的解决办法,可能不实用于所有,但已解决我的需求

 main.setOnTouchListener(new DefaultMapViewOnTouchListener(mainActivity, mainMapView) {
            @Override
            public boolean onSingleTapConfirmed(final MotionEvent e) {
            //点击事件 progressBar为进度圈
               ViewGroup.LayoutParams params = MainActivity.progressBar.getLayoutParams();
               ViewGroup.MarginLayoutParams marginLayoutParams = new ViewGroup.MarginLayoutParams(params);
                 DisplayMetrics dm = mainActivity.getResources().getDisplayMetrics();
                 int  screenHeigth = dm.heightPixels;//获取设备的屏幕高度
                 marginLayoutParams.topMargin=Math.round((e.getY()-(screenHeigth/2))*dm.density);dm.density为屏幕每平方英寸中的像素数量
                marginLayoutParams.leftMargin=e.getX();
                PercentRelativeLayout.LayoutParams params1 = new PercentRelativeLayout.LayoutParams(marginLayoutParams);
                MainActivity.progressBar.postInvalidate();
                progressBar.setLayoutParams(params1);
                                    }
                                    });

在这里插入图片描述

点击屏幕获取到的坐标值是以红色为坐标系,以设备的左上角为原点,黑色为设备屏幕
蓝色为布局的父控件,leftMargin为控件与父控件左侧的距离,topMargin为控件与父控件顶部的距离
若黄色为点击的位置,则需把控件设置在黄色位置,原理是需要将在红色坐标系得到的坐标值,转化为蓝色坐标系中
x坐标转化:
marginLayoutParams.leftMargin=e.getX();
y坐标转化:
marginLayoutParams.topMargin=Math.round((e.getY()-(screenHeigth/2))*dm.density);
屏幕点击的坐标系与蓝色坐标系原点相差屏幕宽度的一半,再乘以每寸的像素数量
将得到后的x,y值设置上去即可

猜你喜欢

转载自blog.csdn.net/qq_38357358/article/details/84637149