Android中自定义组件及自定义属性
16lz
2021-01-26
有时候在做开发的时候,android提供给我们的视图并不能满足我们的要求,所以有时候我们需要自己创建自己的view。
我们只需要将我们想要的继承于View,然后重写里面的方法就可以了。
package com.example.view;import android.content.Context;import android.graphics.Color;import android.util.AttributeSet;import android.widget.TextView;public class MyTextView extends TextView {public MyTextView(Context context, AttributeSet attrs) {super(context, attrs);this.setTextColor(Color.BLUE);// 将字体设置成蓝色}}
然后我们只需要在Layout中使用这个view就可以了。
<?xml version="1.0" encoding="UTF-8"?>
如果我们要自定义属性,就像android:layout_height="wrap_content"这种:
首先我们要学习declare-styleable,它是给自定义控件添加自定义属性时用的。
我们在res/values下建立一个myAttrs.xml
<?xml version="1.0" encoding="utf-8"?>
解释一下上面那些值的属性
Name=”MyTextView” 是在R.java文件生成对应的引用名。
"fontSize"format="dimension" />这个就是自定义的属性名称。在R.java中会生成对应的名字,这个地方是MyTextView_fontSize.
后面的format是定义的你的变量的属性。如果你想学习有关他的更多详细信息,请转向:http://blog.csdn.net/lihengfang/article/details/8290754
在布局文件中我们就可以直接这样使用:
<?xml version="1.0" encoding="UTF-8"?>
其中xmlns:mytextview=http://schemas.android.com/apk/res/com.examp"中的地址是指向R.java所在的目录,我开始也不知道这个是干什么的,但是实验了一次,我就知道了。我开始以为那个是指向我们自定义的那个类,后面才发现,我错了。
我们自定义的View中,我们要获取给定的属性值,如下代码:
package com.example.myviewtest;import android.content.Context;import android.content.res.TypedArray;import android.graphics.Canvas;import android.util.AttributeSet;import android.widget.TextView;public class MyTextView extends TextView {public MyTextView(Context context, AttributeSet attrs, int defStyle) {super(context, attrs, defStyle);// TODO Auto-generated constructor stub}public MyTextView(Context context, AttributeSet attrs) {super(context, attrs);TypedArray ta = context.obtainStyledAttributes(attrs,R.styleable.MyTextView);String name = ta.getString(R.styleable.MyTextView_fontSize);System.out.println("name=" + name);this.setTextSize(ta.getDimension(R.styleable.MyTextView_fontSize, 10));}public MyTextView(Context context) {super(context);}}
http://download.csdn.net/detail/lovecluo/5170841
http://download.csdn.net/detail/lovecluo/5170832
更多相关文章
- 安卓开发----TextView控件属性列表
- 使用系统key文件生成keystore
- EditText_XML属性
- Android(安卓)属性动画(Property Animation) 完全解析 (下)
- buildinfo.sh简要分析
- php脚本生成google play url的下载链接,下载apk并自动反编译后获
- 【Android】第5章(4) 单选和复选
- Android中阻止AlertDialog关闭实例代码
- Android沉浸式状态栏实现示例