Android(安卓)Notes 之 自定义View(1) 之 自定义属性
16lz
2021-01-26
1.因为是自定义属性,所以要创建一个属性的xml文件,这里在value文件夹下创建一个attrs.xml文件
<?xml version="1.0" encoding="utf-8"?><resources> <!--声明的属性集--> <declare-styleable name="MyRect"> <!--自定义的属性,format为color--> <attr name="MyRect_Color" format="color"/> </declare-styleable></resources>
2.自定义的View都必须继承自View,除空的构造方法外还要添加含有AttributeSet
参数的构造函数,用于资源解析器的解析。
/** * Created by tongs on 2016/4/12. * email:tongsdroid@gmail.com */public class MyRect extends View { public MyRect(Context context) { super(context); } /** * 由资源解析器来解析 */ public MyRect(Context context, AttributeSet attrs) { super(context, attrs); //获取xml中的属性和自定义的MyRect属性集. TypedArray ta = context.obtainStyledAttributes(attrs,R.styleable.MyRect); //color的默认值为0x00ff0000 int color = ta.getColor(R.styleable.MyRect_MyRect_Color,0x00ff0000); setBackgroundColor(color); //调用完obtain后要记得recycle回收 ta.recycle(); }}
3.在布局文件中就可以引入自定义的控件MyRect了,也可以在这个文件中引用自定义的属性my_rect:MyRect_Color
,
但要声明命名空间,xmlns:my_rect="http://schemas.android.com/apk/res-auto"
<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:my_rect="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" tools:context="com.android.tongs.custom_view.MainActivity"> <com.android.tongs.custom_view.MyRect android:layout_width="100dp" android:layout_height="100dp" my_rect:MyRect_Color="#ff00ff" /></LinearLayout>
更多相关文章
- SpringBoot 2.0 中 HikariCP 数据库连接池原理解析
- AndroidStudio 2.0 导入(.so)文件方法,以科大讯飞(20021)为例
- android 世界各国英文简写代码 资源文件
- Android中Fragment的使用,切换和返回等问题-刘宇
- 【Android(安卓)Developers Training】 78. 序言:执行网络操作
- android Ubuntu adb: cannot execute binary file: 可执行文件格
- Picasso源码解析
- Android(安卓)Studio 签名证书文件在build.gradle(app)中配置
- Android异步加载访问网络图片-解析json