在项目开发中,可能系统自带的一些widget不能满足我们的需求,这时就需要自定义View。 通过查看系统中的常用widget如Button,TextView,EditText,
在项目开发中,可能系统自带的一些widget不能满足我们的需求,这时就需要自定义View。
通过查看系统中的常用widget如Button,TextView,EditText,他们都继承自View,所以我们在继承自定义View的时候也自然的需要继承View。
1、首先新建一个类LView继承自View
代码如下:
public class LView extends View {
private Paint paint;
public LView(Context context) {
super(context);
}
public LView(Context context, AttributeSet attrs) {
super(context, attrs);
}
@Override
protected void onDraw(canvas canvas) {
super.onDraw(canvas);
paint = new Paint();// new一个画笔
paint.setColor(Color.RED);// 设置画笔颜色
paint.setStyle(Style.FILL);// 设置画笔填充
canvas.drawCircle(50, 50, 40, paint);// 用画笔在画布上添加一个圆,不只可以添加圆,还可以添加矩形等!
paint.setColor(Color.YELLOW);// 设置画笔颜色
canvas.drawText("LView", 50, 50, paint);// 用画笔在画布上添加文字,中间两个参数对应的是坐标。
}
}
2、在layout文件中进行配置
代码如下:
<Button
Android:id="@+id/btn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/hello_world" />
<com.androidstudy.LView
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
运行程序,可以看到如下画面:
--结束END--
本文标题: Android 自定义View的使用介绍
本文链接: https://www.lsjlt.com/news/27926.html(转载时请注明来源链接)
有问题或投稿请发送至: 邮箱/279061341@qq.com QQ/279061341
下载Word文档到电脑,方便收藏和打印~
2024-01-21
2023-10-28
2023-10-28
2023-10-27
2023-10-27
2023-10-27
2023-10-27
回答
回答
回答
回答
回答
回答
回答
回答
回答
回答
0