xml代码如下:package doge.healthcare.activity; import android.content.Context; import android.content.SharedPreferences; import android.os.Bundle; import android.view.MotionEvent; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.RelativeLayout; import android.widget.Toast; import doge.healthcare.R; import doge.healthcare.base.BaseActivity; /** * Created by doge on 2017/5/22. */ public class Measure extends BaseActivity { private RelativeLayout rl_map; private ImageView iv_location; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_second_measure); rl_map= (RelativeLayout) findViewById(R.id.rl_map); iv_location=(ImageView)findViewById(R.id.iv_location); //添加触摸事件 rl_map.setOnTouchListener(new View.OnTouchListener() { @Override public boolean onTouch(View arg0, MotionEvent arg1) { //获取点击位置的坐标 int x = (int) arg1.getX(); int y = (int) arg1.getY(); Toast.makeText(getApplicationContext(),"横坐标"+x+"纵坐标"+y,Toast.LENGTH_SHORT).show(); //设定imageview的位置到点击处 ViewGroup.MarginLayoutParams margin=new ViewGroup.MarginLayoutParams(iv_location.getLayoutParams()); margin.setMargins(x,y, x+margin.width, y+margin.height); RelativeLayout.LayoutParams layoutParams = new RelativeLayout.LayoutParams(margin); iv_location.setLayoutParams(layoutParams); return false; } }); } }
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="match_parent" android:layout_height="match_parent"> <include layout="@layout/title" ></include> <RelativeLayout android:layout_width="match_parent" android:layout_height="match_parent" android:id="@+id/rl_map" android:clickable="true"> <ImageView android:id="@+id/iv_location" android:layout_width="wrap_content" android:layout_height="wrap_content" android:background="@drawable/icon_xihuan_dianji"/> </RelativeLayout> </LinearLayout>
效果如下图
补5-22博客 获取点击坐标并将控件移动到点击位置
最新推荐文章于 2021-02-16 21:43:52 发布