自定义IamgeView,实现区域点击事件

本文介绍了一种自定义ImageView的方法,通过重写onTouchEvent方法来响应触摸事件,并根据触摸位置的不同区域显示相应的提示信息。同时提供了完整的代码实现,包括自定义的RegionCoordView类、布局文件activity_main.xml和MainActivity类。

1.自定义ImageView

public class RegionCoordView extends ImageView {
    private Context mContext;  //上下文

    public RegionCoordView(Context context) {
        this(context, null);
    }

    public RegionCoordView(Context context, AttributeSet attrs) {
        super(context, attrs);
        mContext = context;
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        if (event.getAction() == MotionEvent.ACTION_DOWN) {
            float x = event.getX();
            float y = event.getY();
            int area = 0;
            if (x >= 0 && x < 200 && y > 0 && y < 200) {
                area = 1;
            } else if (x > 200 && x < 400 && y > 0 && y < 200) {
                area = 2;
            } else if (x > 0 && x < 200 && y > 200 && y < 400) {
                area = 3;
            } else if (x > 200 && x < 400 && y > 200 && y < 400) {
                area = 4;
            }
            ((MainActivity) mContext).showClickArea(area);
        }
        return super.onTouchEvent(event);
    }

}

2.activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.example.qd.androidview.MainActivity">

    <com.example.qd.androidview.RegionCoordView
        android:layout_width="400px"
        android:layout_height="400px"
        android:background="#D0D0D0"
        />
</RelativeLayout>

3.MainActivity

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

    }
    public void showClickArea(int area) {
        Toast.makeText(MainActivity.this,"您点击到了第" + area + "块区域!",Toast.LENGTH_SHORT).show();
    }
}

4.运行效果
这里写图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值