自定义视图属性
2016-03-10 14:28
405 查看
1.自定义一个继承View或者View子类的视图类(实现含有AttributeSet的构造函数)
2.编写values/attrs.xml(编写自定义属性)声明两个标签 declare-styleable(name) 和attr(name format)
3.在布局文件中使用自定义的属性(注意前面要加上命名空间 AS下只要输入自定义属性,他会自动提示namespace)
4.在自定义视图类中的构造方法通过TypeArray获取
加深理解
1.AttributeSet可以获取布局文件中定义的所有属性的key和value,但是拿到的是它的ID 而通过TypedArray拿到的是解析后的ID
import android.util.AttributeSet; import android.view.View; /** * Created by 小新 on 2016/3/10. */ public class MyTextView extends View { public MyTextView(Context context, AttributeSet attrs) { super(context, attrs); } }
2.编写values/attrs.xml(编写自定义属性)声明两个标签 declare-styleable(name) 和attr(name format)
<?xml version="1.0" encoding="utf-8"?> <resources> <declare-styleable name="MyTextView"> <attr name="rect_color" format="color"></attr> </declare-styleable> </resources>
3.在布局文件中使用自定义的属性(注意前面要加上命名空间 AS下只要输入自定义属性,他会自动提示namespace)
<com.example.myapplication.MyTextView app:rect_color="#cc99cc" android:layout_width="wrap_content" android:layout_height="wrap_content" />
4.在自定义视图类中的构造方法通过TypeArray获取
public class MyTextView extends View { public MyTextView(Context context, AttributeSet attrs) { super(context, attrs); TypedArray typedArray = context.obtainStyledAttributes(attrs,R.styleable.MyTextView); int color = typedArray.getColor(R.styleable.MyTextView_rect_color,0x0000ff); setBackgroundColor(color); //记得回收资源 typedArray.recycle(); } }
加深理解
1.AttributeSet可以获取布局文件中定义的所有属性的key和value,但是拿到的是它的ID 而通过TypedArray拿到的是解析后的ID
相关文章推荐
- 使用C++实现JNI接口需要注意的事项
- Android IPC进程间通讯机制
- Android Manifest 用法
- [转载]Activity中ConfigChanges属性的用法
- Android之获取手机上的图片和视频缩略图thumbnails
- Android之使用Http协议实现文件上传功能
- Android学习笔记(二九):嵌入浏览器
- android string.xml文件中的整型和string型代替
- i-jetty环境搭配与编译
- android之定时器AlarmManager
- android wifi 无线调试
- Android Native 绘图方法
- Android java 与 javascript互访(相互调用)的方法例子
- android 代码实现控件之间的间距
- android FragmentPagerAdapter的“标准”配置
- Android"解决"onTouch和onClick的冲突问题
- android:installLocation简析
- android searchView的关闭事件
- SourceProvider.getJniDirectories