Android:View上更改鼠标样式及坐标监听

时间:2022-09-10 18:36:56

 

(1)通过OnHoverListener获取鼠标位置:

  appsrcmainjavacomsheldondemoMainActivity.java

     imageView = (ImageView) findViewById(R.id.image_view);
        imageView.setOnHoverListener(new View.OnHoverListener() {
            @SuppressLint({"SetTextI18n", "ResourceType"})
            @Override
            public boolean onHover(View v, MotionEvent event) {
                int what = event.getAction();

                textX.setText("X : "   event.getX());
                textY.setText("Y : "   event.getY());

                switch(what){
                    case MotionEvent.ACTION_HOVER_ENTER:  //鼠标进入view
                        Log.i(TAG, "bottom ACTION_HOVER_ENTER...");
                        getWindow().getDecorView().setPointerIcon(PointerIcon.load(getResources(), R.drawable.pointer_spot_touch_icon)); //修改鼠标样式 break;
                    case MotionEvent.ACTION_HOVER_MOVE:  //鼠标在view上
                        Log.i(TAG, "bottom ACTION_HOVER_MOVE...");
                        break;
                    case MotionEvent.ACTION_HOVER_EXIT:  //鼠标离开view
                        Log.i(TAG, "bottom ACTION_HOVER_EXIT...");
                        break;
                }
                return false;
            }
        });

(2)通过配置文件指定样式资源:

  appsrcmainresdrawablepointer_spot_touch_icon.xml

<?xml version="1.0" encoding="utf-8"?>
<pointer-icon xmlns:android="http://schemas.android.com/apk/res/android"
    android:bitmap="@drawable/ic_visibility_n"
    android:hotSpotX="16dp"
    android:hotSpotY="16dp" />