Android自定义View的一些理解
来源:互联网 发布:投资数据库终端 编辑:程序博客网 时间:2024/06/05 14:06
在我们写布局文件时,像button,ImageView,都是一个个view。那自定义view就可以理解为,”newbutton“或者"newiamgeView"。
那么在button类似的组件中,我们通过设置width,hight就可以改变他们的大小,这些属性当然是前辈们完成好,供我们使用的。
那现在我们想给我们自定义的view,添加一个属性,比如一个文本字体大小,或者文本的字体颜色,那要怎么做呢。可能你会想,咦为什么不直接写android:textSize=""这样去设置呢,那如果你这个View并没有像button有text这个属性,你又怎么设置呢。
好比你这个view中,定义了一个paint,想用paint画一个蓝色的园,那你还想android:textColor=“”去设置吗?明显是不行的嘛。
那又有同学想了,那简单啊就在onDraw直接定义就好了。
protected void onDraw(Canvas canvas){paint.setColor(Color.BLUE);}但,你们想想看一个属性如果写死的话,那这个view就不好用了,比如你想设置button的width,然而它是写死的,你还会用它吗,是一个道理。
那要怎么实现属性的自定义呢。首先你需要
- 在res/values文件下定义一个attrs.xml文件.代码如下:
- <?xml version="1.0" encoding="utf-8"?>
- <resources>
- <declare-styleable name="MyView">
- <attr name="textColor" format="color" />
- <attr name="textSize" format="dimension" />
- </declare-styleable>
- </resources>
然后在myView的构造函数中去获得
- public MyView(Context context,AttributeSet attrs)
- {
- super(context,attrs);
- mPaint = new Paint();
- //
- TypedArray a = context.obtainStyledAttributes(attrs,
- R.styleable.MyView);
- int textColor = a.getColor(R.styleable.MyView_textColor,
- 0XFFFFFFFF);
- float textSize = a.getDimension(R.styleable.MyView_textSize, 36);
- mPaint.setTextSize(textSize);
- mPaint.setColor(textColor);
- a.recycle();
- }
可能有同学奇怪你这步不也是写死了的吗,其实最后这个参数是默认值,就是不去设置时取这个值
- int textColor = a.getColor(R.styleable.MyView_textColor,
- 0XFFFFFFFF);
然后在xml文件的使用。
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:test="http://schemas.android.com/apk/res/com.android.tutor" android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent" > <TextView android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="@string/hello" /> <com.android.tutor.MyView android:layout_width="fill_parent" android:layout_height="fill_parent" test:textSize="20px" test:textColor="#fff" /> </LinearLayout>
上述的代码来自http://weizhulin.blog.51cto.com/1556324/311453
0 0
- Android自定义View的一些理解
- Android 自定义View的一点理解
- Android 自定义View onMeasure 的理解
- Android杂谈(8)关于自定义View的一些实践+遮罩理解
- Android 对View的一些理解
- Android View 系统的一些理解
- Android 自定义View的一些总结
- android 积累一些自定义view的知识
- Android 自定义View的一些使用技巧
- Android 自定义View onMeasure理解
- 深入理解Android自定义View
- android中对自定义View的onMeasure()方法的理解
- Android自定义View的一些不知道的细节
- android 自定义view时,重写onDraw(),对Canvas的理解
- Android自定义view的三个构造函数理解
- Android学习札记3:对View.MeaureSpec的一些理解
- android 自定义view所需要的一些东西
- 自定义View的理解体会
- 华为笔试题 (消灭终极boss)
- MySQL operation
- 利用Google Analytics Api 获取数据——Google-api-python-client配置问题(一)
- centos7 cannot find a valid baseurl for repo base
- Linux Is Not Matrix——zabbix监控mysql
- Android自定义View的一些理解
- css学习
- OpenCV 视频与图片序列相互转换 VideoWriter生成视频流
- OpenCV读入图片序列进行HOG行人检测并保存为视频
- Eigen中的基本函数
- Leetcode 137: (Single Number II)
- 用于并行计算的多线程数据结构,第 1 部分: 设计并发数据结构
- 关于java中的protected一点理解
- 复杂链表的复制