Android中自定义属性基本步骤

这次只是说明最简单的自定义属性流程

1. 创建资源文件: resources/attr.xml

<?xml version="1.0" encoding="utf-8"?><resources>    <declare-styleable name="test">        <attr name="test" format="string" />        <attr name="testArr" format="integer" />    declare-styleable>resources>

2. 自定义view类

public class MyTextView extends View{    private static final String TAG = "MyTextView";    public MyTextView(Context context, AttributeSet attrs) {        super(context, attrs);        TypedArray ta = context.obtainStyledAttributes(attrs,R.styleable.test);        String text = ta.getString(R.styleable.test_testArr);        int textAttr = ta.getInteger(R.styleable.test_text, -1);        Log.e(TAG, "text:"+text+",textAttr:"+textAttr);        ta.recycle();    }}

3. 在布局文件中使用

<?xml version="1.0" encoding="utf-8"?><RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"    xmlns:tools="http://schemas.android.com/tools"    xmlns:yxm="http://schemas.android.com/apk/res-auto"    android:layout_width="match_parent"    android:layout_height="match_parent"    tools:context="org.xm.customview.MainActivity">    <org.xm.customview.MyTextView        android:layout_width="100dp"        android:layout_height="200dp"        yxm:testArr="20"        yxm:text="xiaoming" />RelativeLayout>

注意

androidstudio中使用:xmlns:yxm="http://schemas.android.com/apk/res-auto"自动导入命名控件
如果在eclipse中要使用完成的包名,如:xmlns:sdf="http://schemas.android.com/apk/res/org.xm.customview"
给自定义属性添加参数使用制定定义的命名空间,例如: yxm:testArr="20"

4. 实现自定义View,获取自定义属性

public class MyTextView extends View{    private static final String TAG = "MyTextView";    public MyTextView(Context context, AttributeSet attrs) {        super(context, attrs);        TypedArray ta = context.obtainStyledAttributes(attrs,R.styleable.test);        String text = ta.getString(R.styleable.test_text);        int textAttr = ta.getInteger(R.styleable.test_testArr, -1);        Log.e(TAG, "text:"+text+",textAttr:"+textAttr);        ta.recycle();    }}

注意

R.styleable.test_text中 text_是自动添加的(必须写),然后添加属性名字text

所以最后会打印:text:xiaoming,textAttr:20, 还是很简单的吧!

更多相关文章

  1. Android 制定的ROM包(文件系统根目录结构分析)
  2. Android中xml文件读写
  3. Android 属性系统: Android Property System
  4. ImageView ScaleType 属性值的意义
  5. Android 基本属性绘制文本对象FontMetrics介绍
  6. Android中Manifest.xml配置文件
  7. android之layout配置文件解读
  8. android 从tomcat读取文件出错:connect failed: ECONNREFUSED

随机推荐

  1. HTML5中window.postMessage,在两个页面之
  2. 如何集中无序列表?
  3. 如何使用一个锚标记打开多个链接
  4. 我正在尝试使用带有post方法的AJAX将用户
  5. 如何只用HTML和CSS构建一个特殊的多边形(
  6. 【HTML】让标签文本自动换行
  7. 在Makefile.am中添加make install 的安装
  8. 如何在网站中找到未使用的图像和CSS样式?
  9. 180225-第一百零七天【html链接,头部】
  10. HTML5之canvas标签(上)