简体   繁体   English

如何在android中创建自定义形状的按钮

[英]how to create custom shaped buttons in android

I knew this question is a duplicate but i couldnt figure out the solution for creating custom shaped buttons say circular,oval etc. 我知道这个问题是重复的,但我想不出创建圆形,椭圆形等自定义形状按钮的解决方案。

Doubt1: My objective is to perform an action only when the area inside the shape is clicked, nothing should be performed just outside the shape( say only circular area has to be atttached with a listener) 疑点一:我的目标是仅在单击形状内的区域时执行操作,而不要在形状外进行任何操作(例如,仅圆形区域必须与侦听器连接)

Doubt 2: Can i use png pictures of the shapes as backgrounds or should I use only shapes to draw them. 怀疑2:我可以使用形状的png图片作为背景,还是只使用形状绘制它们? Pls give me a simple solution... 请给我一个简单的解决方案...

Thanks in advance.. 提前致谢..

You can use ImageButtons and set oval or circular shaped images as background. 您可以使用ImageButtons并将椭圆形或圆形的图像设置为背景。 I hope it helps 希望对您有所帮助

try this link it will help you to create custom button. 试试这个链接,它将帮助您创建自定义按钮。 http://angrytools.com/android/button/ http://angrytools.com/android/button/

all you have to do is save the button.xml file in your drawable folder and then set your button background as 所有您需要做的就是将button.xml文件保存在可绘制文件夹中,然后将按钮背景设置为

android:background="@drawable/button.xml"

You should use ShapeDrawable for the job. 您应该对作业使用ShapeDrawable If you made a circle button for example, nothing will happen if you clicked outside the circle area. 例如,如果您制作了一个圆圈按钮,则在圆圈区域之外单击将不会发生任何事情。

For example inside your drawable folder, make xml file circle_button: 例如,在您的可绘制文件夹中,将xml文件设置为circle_button:

<?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="2sp" android:color="#fff" />
</shape>

and in your button, set background="@drawable/circle_button" 并在您的按钮中设置background="@drawable/circle_button"

As @MSaudi said ShapeDrawable will give you shaped buttons. 正如@MSaudi所说,ShapeDrawable将为您提供形状的按钮。

If you wanted to use PNG's that is more difficult. 如果您想使用PNG,那就更困难了。

I would approach it by extending the Button class and overriding the onTouchEvent method to only register a click when inside the shape required (possibly by checking if the view is transparent at the click location). 我将通过扩展Button类并重写onTouchEvent方法来仅在所需形状内注册一次单击(可能通过检查视图在单击位置是否透明)来实现此目的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM