Android自定义控件中常见的方法
16lz
2022-07-27
/** * onMeasure方法的作用时测量空间的大小 * @param widthMeasureSpec * @param heightMeasureSpec */ @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { super.onMeasure(widthMeasureSpec, heightMeasureSpec); //设定默认值,当属性为wrap_comtent时使用,使用match_parent时是精确模式 int defaultWidthSpecSize = 200; int defaultHeightSpecSize = 200; int widthSpecMode = MeasureSpec.getMode(widthMeasureSpec); int heightSpecMode = MeasureSpec.getMode(heightMeasureSpec);/** * Mode取值: * UNSPECIFIED:未指定模式,View想多大就多大,父容器不做限制,一般用于系统内部的测量。 * AT_MOST:最大模式,对应于wrap_comtent属性,只要尺寸不超过父控件允许的最大尺寸就行。 * EXACTLY:精确模式,对应于match_parent属性和具体的数值,父容器测量出View所需要的大小,也就是specSize的值。 */ if (widthSpecMode == MeasureSpec.EXACTLY) { defaultWidthSpecSize = MeasureSpec.getSize(widthMeasureSpec); } if (heightSpecMode == MeasureSpec.EXACTLY) { defaultHeightSpecSize = MeasureSpec.getSize(heightMeasureSpec); } setMeasuredDimension(defaultWidthSpecSize, defaultHeightSpecSize); }
自定义属性:
attrs.xml文件
<?xml version="1.0" encoding="utf-8"?>
在自定义View的构造函数中获取
public CustomView(Context context, AttributeSet attrs) { super(context, attrs); TypedArray ta = context.obtainStyledAttributes(attrs, R.styleable.CustomView); mColor = ta.getColor(R.styleable.CustomView_myColor, Color.GREEN); //获取完成后及时释放资源 ta.recycle(); init(); }
更多相关文章
- Android系统配置数据库注释(settings.db)
- Android开发——Android搜索框架(二)
- [Android] ACTION_GET_CONTENT与ACTION_PICK的区别
- Android(安卓)UI系列 - 布局 - 目录
- Android——Activity四种启动模式
- android Manifest.xml选项-android:ConfigChanges
- linearLayout 和 relativeLayout的属性区别
- Android(安卓)属性动画(Property Animation) 完全解析 (下)
- Android修改字体样式