Android studio中Custom View使用方法
来源:互联网 发布:吉首大学网络自助中心 编辑:程序博客网 时间:2024/05/22 05:21
CustomView是自定义View基类,如果你的自定义View继承这个类则能自动获取到View大小与一个默认的Paint,可以帮助你节省部分代码,示例如下:
通常的自定义View
public class MyView extends View { private int mWidth; private int mHeight; private Paint mPaint; public MyView(Context context) { this(context, null); } public MyView(Context context, AttributeSet attrs) { super(context, attrs); // 初始化画笔 mPaint.setColor(Color.GRAY); } @Override protected void onSizeChanged(int w, int h, int oldw, int oldh) { super.onSizeChanged(w, h, oldw, oldh); mWidth = w; mHeight = h; } @Override protected void onDraw(Canvas canvas) { super.onDraw(canvas); // 获取View宽高与画笔并根据此绘制内容 canvas.translate(mWidth / 2, mHeight / 2); canvas.drawCircle(0,0,100,mPaint); }}
继承CustomView
public class MyView extends CustomView { public MyView(Context context) { this(context, null); } public MyView(Context context, AttributeSet attrs) { super(context, attrs); // 初始化画笔 mDefaultTextPaint.setColor(Color.GRAY); } @Override protected void onDraw(Canvas canvas) { super.onDraw(canvas); // 获取View宽高与画笔并根据此绘制内容 canvas.translate(mViewWidth / 2, mViewHeight / 2); canvas.drawCircle(0,0,100,mDeafultPaint); }}
Android studio的好处,这里就不错过多的说明了。studio中内置了很多的模版可供使用,大大的简化了工作量。在实际开发中,android自带的各类控件可能无法满足我们的需求,这就需要我们自定义控件,下面介绍一下Custom View的方法。
第一步:studio界面,File->New->UI Component->Custom View,sutdio自动创建一个布局、CustomView类以及一个自定义属性XML。
接下来,由于gradle默认自定义属性为
xmlns:XXX="http://schemas.android.com/apk/res-auto"形式,来取代 xmlns:XXX="http://schemas.android.com/apk/res/包名"的形式
所以需要在使用该自定义控件时,在所遇的布局中,手动加上该声明。例如:我在MainActivity的布局中使用该控件,且用到自定义属性,需要在MainActivity的布局声明中添加 xmlns:XXX="http://schemas.android.com/apk/res-auto"后再使用。
由于自动生成的控件类,在布局中使用时,会调用CustomView(Context context, AttributeSet attrs)构造函数,其中会使用到自定义的某些属性,所以需要在主布局中添加上相应的自定义属性,或者删除掉相应的调用自定义属性的代码,否则app会因为非法访问崩溃。
阅读全文
0 0
- Android studio中Custom View使用方法
- Android studio中Custom View使用方法
- Android custom view
- Android Custom View NullPointerException
- android custom view
- Android - Custom View
- android : custom view
- Android Studio中AIDL使用方法
- Android Studio中AIDL使用方法
- android 之 custom view(一)
- Create a custom view in Android || 在 Android 中创建一个自定义 View
- Android Custom View (自定义 View)
- 浅谈Android Studio 中Gradle的使用方法
- RecyclerView在Android studio中使用方法
- Android Custom view —- bottom sheet
- Android Custom View---Floating Action Button Menu
- Android Custom View --- Circular(环形条)
- Android Custom View ---->invalidate() 、postInvalidate() and requestLayout()
- supplied parameters do not match any signature of call target html
- android actionbar自定义View并添加点击事件
- JavaScript学习总结(二)——逻辑Not运算符详解
- Unity3D async await异步语法用法
- Caffe Pythonlayer编写
- Android studio中Custom View使用方法
- html笔记
- qt之QTableWidget表头塌陷和光标移动
- 深入理解js中的apply、call、bind
- 联系我
- Greenplum 基本使用命令
- 资讯精选 | 软件开发行业_产品经理的痛点_简单分析
- Spring JdbcTemplate方法详解
- servlet本质