广告
返回顶部
首页 > 资讯 > 精选 >Android入门篇自定义Button控件
  • 374
分享到

Android入门篇自定义Button控件

Android 2023-09-22 11:09:12 374人浏览 安东尼
摘要

在Android中,可以通过继承Button类来创建自定义Button控件。下面是一个简单的例子,演示如何创建一个带有圆角背景和自定

Android中,可以通过继承Button类来创建自定义Button控件。下面是一个简单的例子,演示如何创建一个带有圆角背景和自定义字体的Button控件。
首先,创建一个名为CustomButton的Java类,继承自Button类:
```java
public class CustomButton extends Button {
public CustomButton(Context context) {
super(context);
init();
}
public CustomButton(Context context, AttributeSet attrs) {
super(context, attrs);
init();
}
public CustomButton(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
init();
}
private void init() {
// 设置背景为圆角
GradientDrawable drawable = new GradientDrawable();
drawable.setCornerRadius(10);
drawable.setColor(Color.BLUE);
setBackground(drawable);
// 设置字体为自定义字体
Typeface typeface = Typeface.createFromAsset(getContext().getAssets(), "custom_font.ttf");
setTypeface(typeface);
}
}
```
在init()方法中,我们创建了一个GradientDrawable对象,并通过setCornerRadius()方法设置了圆角的半径,再通过setColor()方法设置了背景颜色。然后,通过setBackground()方法将背景设置为我们创建的drawable对象。
接下来,我们通过Typeface类来加载自定义字体文件,将其设置为按钮的字体。
最后,我们需要在布局文件中使用我们自定义的Button控件。在xml布局文件中,可以使用全限定名来引用自定义控件:
```xml
ion.CustomButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Custom Button" />
```
这样,就完成了一个简单的自定义Button控件。现在,运行应用程序,可以看到按钮的背景颜色变为蓝色,并且字体变为我们自定义的字体。
注意:在使用自定义字体时,需要将字体文件放置在assets文件夹中,并在代码中使用正确的文件路径进行加载。

--结束END--

本文标题: Android入门篇自定义Button控件

本文链接: https://www.lsjlt.com/news/415147.html(转载时请注明来源链接)

有问题或投稿请发送至: 邮箱/279061341@qq.com    QQ/279061341

本篇文章演示代码以及资料文档资料下载

下载Word文档到电脑,方便收藏和打印~

下载Word文档
猜你喜欢
软考高级职称资格查询
编程网,编程工程师的家园,是目前国内优秀的开源技术社区之一,形成了由开源软件库、代码分享、资讯、协作翻译、讨论区和博客等几大频道内容,为IT开发者提供了一个发现、使用、并交流开源技术的平台。
  • 官方手机版

  • 微信公众号

  • 商务合作