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

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


<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.运行效果
自定义IamgeView,实现区域点击事件_第1张图片

你可能感兴趣的:(菜鸟的Android)