我在Android Studio中制作了这个圆形按钮:
我使用了自定义背景。问题是图像中突出显示的黄色区域是可点击的。我想将可点击区域缩小到红色圆圈。
有没有办法做这样的事情?
答案 0 :(得分:2)
您无法删除图片的透明区域。因为它是你形象的一部分。
任何类型的图像始终具有矩形。如果图像的边角是透明的,并不意味着角落处的像素与图像分开!那些像素总是被图像占据而你无法删除该区域。
尚未创建可以将图像的透明区域与图像本身分开的库。
答案 1 :(得分:1)
有一篇关于clickable area of image的帖子,但是......这里可能无法解决这个问题。
相反,您应该使用OnTouchListener来获取触摸事件的x和y,然后计算并比较中心与偶数之间的距离,以确定这是否是值点击。
答案 2 :(得分:0)
迟到总比没有好...
是,如果您通过实现View.OnTouchListener或覆盖onTouchEvent()来拦截和过滤触摸事件,则可以手动将可点击区域缩小为红色圆圈。后者要求您对按钮进行子类化,这很容易,但可能并不理想,因此下面是使用View.OnTouchListener
来完成工作的示例:
OvalTouchAreaFilter.java:
public class OvalTouchAreaFilter implements View.OnTouchListener {
private boolean mIgnoreCurrentGesture;
public TouchAreaFilter() {
mIgnoreCurrentGesture = false;
}
public boolean isInTouchArea(View view, float x, float y) {
int w = view.getWidth();
int h = view.getHeight();
if(w <= 0 || h <= 0)
return false;
float xhat = 2*x / w - 1;
float yhat = 2*y / h - 1;
return (xhat * xhat + yhat * yhat <= 1);
}
@SuppressLint("ClickableViewAccessibility")
@Override
public boolean onTouch(View view, MotionEvent event) {
int action = event.getActionMasked();
if(action == MotionEvent.ACTION_DOWN) {
mIgnoreCurrentGesture = !this.isInTouchArea(view, event.getX(), event.getY());
return mIgnoreCurrentGesture;
}
boolean ignoreCurrentGesture = mIgnoreCurrentGesture;
if(action == MotionEvent.ACTION_UP || action == MotionEvent.ACTION_CANCEL)
mIgnoreCurrentGesture = false;
return ignoreCurrentGesture;
}
}
内部活动onCreate():
View button = findViewById(R.id.my_button);
button.setOnTouchListener(new OvalTouchAreaFilter());
请注意:
isInTouchArea()
可以任意实现,以将可点击区域设置为所需的任何形状,甚至可能取决于复杂条件,例如按钮的背景图像等。
setOnTouchListener()
并非特定于Button
类。该解决方案可用于任何类型的视图。
仅根据盲目过滤所有触摸消息的X和Y位置(例如,根据答案here中的建议)来盲目过滤所有的触摸消息不是一个好方法,因为这样会破坏MotionEvent consistency guarantee。相反,此解决方案可以过滤出完整手势(MotionEvent
的顺序以ACTION_DOWN
开始,以ACTION_UP
/ ACTION_CANCEL
结尾,可能还有许多其他手势ACTION_MOVE
之间的动作基于其起始坐标。这意味着该方法在多点触摸情况下不会中断。
答案 3 :(得分:-1)
像这样创建xml drawable:
将其保存为drawable文件夹中的round_button.xml
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="oval">
<solid android:color="#9F2200"/>
<stroke android:width="2dp" android:color="#fff" />
</shape>
并将其设置为xml中Button的背景,如下所示:`
<Button
android:layout_width="50dp"
android:layout_height="50dp"
android:background="@drawable/round_button"
android:gravity="center_vertical|center_horizontal"
android:text="hello"
android:textColor="#fff" />