补5-22博客 获取点击坐标并将控件移动到点击位置

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代码如下:
<?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>


效果如下图
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值