declare-styleable是给自定义控件添加自定义属性用的

1.首先,先写attrs.xml

<pre name="code" class="html"><?xml version="1.0" encoding="utf-8"?><resources>    <declare-styleable name="TestAttr">        <attr name="name" format="reference" />        <attr name="age">            <flag name="child" value="10" />            <flag name="young" value="18" />            <flag name="oldman" value="60" />        </attr>        <attr name="textSize" format="dimension" />       </declare-styleable></resources>

  

reference指的是是从string.xml引用过来flag是自己定义的,类似于android:gravity="top"
dimension 指的是是从dimension.xml里引用过来的内容.注意,这里如果是dp那就会做像素转换
  

2.在布局文件里的写法

<pre name="code" class="html"><?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"    xmlns:attrstest="http://schemas.android.com/apk/res/com.arlos.attrstest"    android:layout_width="fill_parent"    android:layout_height="fill_parent"    android:orientation="vertical" >s    <com.arlos.attrstest.MyTestView        android:id="@+id/tvTest"        android:layout_width="fill_parent"        android:layout_height="wrap_content"        attrstest:name="@string/myname"         android:gravity="top"        attrstest:age="young"        attrstest:textSize="@dimen/aa"        android:text="@string/hello" /></LinearLayout>



2.1先引用这个dtd

xmlns:attrstest="http://schemas.android.com/apk/res/com.arlos.attrstest"
attrstest是随便写的.后面的包名是你所在的项目的根包.也就是在manifest里的com.arlos.attrstest

2.2 在自定义的控件里写属性


  

3. 最后在控件的构造方法里取得这些值

public class MyTestView extends TextView {    public MyTestView(Context context, AttributeSet attrs) {        super(context, attrs);        TypedArray tArray = context.obtainStyledAttributes(attrs,                R.styleable.TestAttr);        String name = tArray.getString(R.styleable.TestAttr_name);        System.out.println("name = " + name);        int age = tArray.getInt(R.styleable.TestAttr_age, 200);        System.out.println("age = " + age);         float demin = tArray.getDimension(R.styleable.TestAttr_textSize,0);         System.out.println("demin = " + demin);        tArray.recycle();    }}



更多相关文章

  1. Android(安卓)- Unable to execute dex: Multiple dex files def
  2. Android(安卓)自定义控件
  3. 安卓进阶第五篇之常见动画的使用
  4. Android(安卓)Toolbar的详细使用步骤
  5. android自定义属性attrs
  6. 我的Xamarin开发配置
  7. android Application Component研究之Activity(一)
  8. Android中可自由移动悬浮窗口的实现
  9. Android使用Fragment,不能得到Fragment内部控件,findViewById()结

随机推荐

  1. Android获取本应用的MD5值
  2. Android使用Bundle进行数据传递分析
  3. Android(安卓)SharedPreferences的使用
  4. 基于android背景选择器selector的用法汇
  5. 关于 Android 平台开发相关的有哪些推荐
  6. android相机拍照
  7. Android开发常用工具查询网站链接
  8. android stdio 设置屏幕旋转后保存数据
  9. Google IO 2011最新技术分享
  10. Android核心模块及相关技术介绍