如何使用ShapeDrawable创建可点击的按钮? [英] How-to create a clickable Button with a ShapeDrawable?
问题描述
我正在尝试在Canvas上绘制形状并获取有关用户在该Canvas上执行的点击的信息.
I'm trying to draw a shape on a Canvas and get information about the clicks that the user performs on that Canvas.
我创建了一个扩展Button类的类.
I created a class which extends the Button class.
class CustomDrawableButton extends Button {
private final ShapeDrawable mDrawable;
int x = 50;
int y = 50;
int width = 30;
int height = 30;
public CustomDrawableButton (Context context) {
super(context);
mDrawable = new ShapeDrawable (new OvalShape ());
mDrawable.getPaint().setColor(Color.GREEN);
mDrawable.setBounds(x, y, x + width, y + height);
}
protected void onDraw(Canvas canvas) {
mDrawable.draw(canvas);
}
}
然后,在还扩展了View的类中,我添加了实例化和侦听器:
Then, in a class which also extends View, I added the instantiation and a listener:
CustomDrawableButton mCustomDrawableButton = new CustomDrawableButton(getBaseContext());
layout.addView(mCustomDrawableButton);
mCustomDrawableButton.draw(canvas);
mCustomDrawableButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
System.out.println("Yey clicked");
Toast.makeText(view.getContext(), "Yey", Toast.LENGTH_LONG).show();
}});
执行此操作时,它无法检测到图像/按钮上的点击.我已经读过ShapeDrawable对象不能是可单击的",但是我一直期望它能够工作,因为我正在扩展Button(它是一个视图,并且是可单击的").
When this is executed, it is not able to detect the clicks on the image / button. I have read that ShapeDrawable objects can't be "clickable", but I was expecting this to work since I'm extending the Button (which is a View and is "clickable").
这可能吗?如果不是这样,您能否引导我获得某种方式,以获取有关在画布"或视图"上按下的屏幕坐标的信息?
Is this possible? If not this way, can you direct me to some way to get information about the screen coordinates that were pressed on a Canvas or a View ?
谢谢.
推荐答案
在进行一些搜索之后,这里有一个教程,展示了如何通过获取触摸屏的位置来使用它.
After some searching here's a tutorial that shows how to do it using by getting the touched screen position.
http://marakana.com/tutorials/android/2d-graphics -example.html
仍然不知道如何通过将touched事件自动绑定到按钮来做到这一点.如果有人知道该怎么做,请这样说.
Still don't know how to do it by automatically binding the touched event to a button. If anyone knows how to do it, please say so.
谢谢.
这篇关于如何使用ShapeDrawable创建可点击的按钮?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!