自定义属性和样式主题

均属于笔记,仅供个人参考,有问题欢迎指正

Android自定义属性,属性类型format详解

1. reference:参考某一资源ID。

    (1)属性定义:

            <declare-styleable name = "名称">

                  <attr name = "background" format = "reference" />

            </declare-styleable>

    (2)属性使用:

            <ImageView

                    android:layout_width = "42dip"

                    android:layout_height = "42dip"

                    android:background = "@drawable/图片ID"

                    />

2. color:颜色值。

    (1)属性定义:

            <declare-styleable name = "名称">

                  <attr name = "textColor" format = "color" />

            </declare-styleable>

    (2)属性使用:

            <TextView

                    android:layout_width = "42dip"

                    android:layout_height = "42dip"

                    android:textColor = "#00FF00"

                    />

3. boolean:布尔值。

    (1)属性定义:

            <declare-styleable name = "名称">

                  <attr name = "focusable" format = "boolean" />

            </declare-styleable>

    (2)属性使用:

            <Button

                    android:layout_width = "42dip"

                    android:layout_height = "42dip"

                    android:focusable = "true"

                    />

4. dimension:尺寸值。

    (1)属性定义:

            <declare-styleable name = "名称">

                  <attr name = "layout_width" format = "dimension" />

            </declare-styleable>

    (2)属性使用:

            <Button

                    android:layout_width = "42dip"

                    android:layout_height = "42dip"

                    />

5. float:浮点值。

    (1)属性定义:

            <declare-styleable name = "AlphaAnimation">

                  <attr name = "fromAlpha" format = "float" />

                  <attr name = "toAlpha" format = "float" />

            </declare-styleable>

    (2)属性使用:

            <alpha

                  android:fromAlpha = "1.0"

                  android:toAlpha = "0.7"

                  />

6. integer:整型值。

    (1)属性定义:

            <declare-styleable name = "AnimatedRotateDrawable">

                  <attr name = "visible" />

                  <attr name = "frameDuration" format="integer" />

                  <attr name = "framesCount" format="integer" />

                  <attr name = "pivotX" />

                  <attr name = "pivotY" />

                  <attr name = "drawable" />

            </declare-styleable>

    (2)属性使用:

            <animated-rotate

                  xmlns:android = "http://schemas.android.com/apk/res/android" 

                  android:drawable = "@drawable/图片ID" 

                  android:pivotX = "50%" 

                  android:pivotY = "50%" 

                  android:framesCount = "12" 

                  android:frameDuration = "100"

                  />

7. string:字符串。

    (1)属性定义:

            <declare-styleable name = "MapView">

                  <attr name = "apiKey" format = "string" />

            </declare-styleable>

    (2)属性使用:

            <com.google.android.maps.MapView

                    android:layout_width = "fill_parent"

                    android:layout_height = "fill_parent"

                    android:apiKey = "0jOkQ80oD1JL9C6HAja99uGXCRiS2CGjKO_bc_g"

                    />

8. fraction:百分数。

    (1)属性定义:

            <declare-styleable name="RotateDrawable">

                  <attr name = "visible" />

                  <attr name = "fromDegrees" format = "float" />

                  <attr name = "toDegrees" format = "float" />

                  <attr name = "pivotX" format = "fraction" />

                  <attr name = "pivotY" format = "fraction" />

                  <attr name = "drawable" />

            </declare-styleable>

    (2)属性使用:

            <rotate

                  xmlns:android = "http://schemas.android.com/apk/res/android"

              android:interpolator = "@anim/动画ID"

                  android:fromDegrees = "0"

              android:toDegrees = "360"

                  android:pivotX = "200%"

                  android:pivotY = "300%"

              android:duration = "5000"

                  android:repeatMode = "restart"

                  android:repeatCount = "infinite"

                  />

9. enum:枚举值。

    (1)属性定义:

            <declare-styleable name="名称">

                  <attr name="orientation">

                          <enum name="horizontal" value="0" />

                          <enum name="vertical" value="1" />

                  </attr>           

            </declare-styleable>

    (2)属性使用:

            <LinearLayout

                    xmlns:android = "http://schemas.android.com/apk/res/android"

                    android:orientation = "vertical"

                    android:layout_width = "fill_parent"

                    android:layout_height = "fill_parent"

                    >

            </LinearLayout>

10. flag:位或运算。

    (1)属性定义:

            <declare-styleable name="名称">

                    <attr name="windowSoftInputMode">

                            <flag name = "stateUnspecified" value = "0" />

                            <flag name = "stateUnchanged" value = "1" />

                            <flag name = "stateHidden" value = "2" />

                            <flag name = "stateAlwaysHidden" value = "3" />

                            <flag name = "stateVisible" value = "4" />

                            <flag name = "stateAlwaysVisible" value = "5" />

                            <flag name = "adjustUnspecified" value = "0x00" />

                            <flag name = "adjustResize" value = "0x10" />

                            <flag name = "adjustPan" value = "0x20" />

                            <flag name = "adjustNothing" value = "0x30" />

                    </attr>       

            </declare-styleable>

    (2)属性使用:

            <activity

                  android:name = ".StyleAndThemeActivity"

                  android:label = "@string/app_name"

                  android:windowSoftInputMode = "stateUnspecified | stateUnchanged | stateHidden">

                  <intent-filter>

                          <action android:name = "android.intent.action.MAIN" />

                          <category android:name = "android.intent.category.LAUNCHER" />

                  </intent-filter>

            </activity>

    注意:

    属性定义时可以指定多种类型值。

    (1)属性定义:

            <declare-styleable name = "名称">

                  <attr name = "background" format = "reference|color" />

            </declare-styleable>

    (2)属性使用:

            <ImageView

                    android:layout_width = "42dip"

                    android:layout_height = "42dip"

                    android:background = "@drawable/图片ID|#00FF00"

                    />


自定义属性必须和自定义的view结合使用,即是自定义的属性就是为自定义的控件服务的。而自定义样式或主题是将项目中常用的系统属性抽取出来,减少代码的重复。样式用于view主题用于Activity或Application。

一,自定义属性时命名空间中res与res-auto的区别

通常我们在布局文件中使用自定义属性的时候会这样写xmlns:app="http://schemas.android.com/apk/res/包路径"但如果你当前工程是做为lib使用,那么你如上所写 ,会出现找不到自定义属性的错误 。这时候你就必须 写成xmlns:app="http://schemas.android.com/apk/res-auto/包路径"

Android 可以自定义View,同时我们也可以为我们的自定义的View添加自定义属性,对系统的控件实现扩展,使用方式如同系统控件在xml布局文件中的使用形式。

扩展方式:自定义属性,然后再布局文件中使用这些属性,在自定义View中获取这些自定义属性的值。

具体方式如下:

1.定义属性:在res/values目录下创建attrs.xml文件

<?xml version="1.0" encoding="utf-8"?> 

<resources> 

    <declare-styleable name="RoundAngleImageView"> 

        <attr name="roundWidth" format="dimension" /> 

        <attr name="roundHeight" format="dimension" /> 

    </declare-styleable> 

</resources> 

其中name为该属性集的名字,在第三部获取属性值时roundWidth = a.getDimensionPixelSize(R.styleable.RoundAngleImageView_roundWidth, roundWidth);需要在每个参数名前面添加这个name和下划线(如:RoundAngleImageView_roundWidth)。

属性的类型即format有string , integer , dimension , reference , color , enum.,如果可以同时使用不同的类型。用”|“分割。

枚举类型的设置略有不同

<attr name="flowDirection" format="enum"> 

          <enum name="leftToRight" value="0" /> 

          <enum name="topDown" value="1" /> 

          <enum name="rightToLeft" value="2" /> 

          <enum name="bottomUp" value="3" /> 

      </attr> 

2.在布局文件中使用属性

<?xml version="1.0" encoding="utf-8"?> 

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" 

    xmlns:app="http://schemas.android.com/apk/res-auto" 

    android:orientation="vertical" 

    android:layout_width="fill_parent" 

    android:layout_height="fill_parent" 

    > 

    <com.liupan.app.RoundImage android:id="@+id/roundImage" 

        android:layout_width="fill_parent" 

        android:layout_height="wrap_content" 

        android:layout_alignParentBottom="true" 

        android:background="@drawable/control_bar" 

        android:gravity="center" 

        app:roundWidth = "5dp" 

        app:roundHeight="10dp"/> 

</RelativeLayout> 

首先需要

xmlns:app="http://schemas.android.com/apk/res-auto" 

xmlns后边的app这个名字可以任意取,属性设置就是使用这个名字开头。

3. 在自定义组件中的构造函数中获取设置的属性值

public RoundCornerImageView(Context context) { 

      super(context); 

      init(context, null); 

  } 


  public RoundCornerImageView(Context context, AttributeSet attrs) { 

      super(context, attrs); 

      init(context, attrs); 

  } 


  public RoundCornerImageView(Context context, AttributeSet attrs, int defStyle) { 

      super(context, attrs, defStyle); 

      init(context, attrs); 

  } 

第一个构造函数没有AttributeSet参数,我们需要设置默认值。

在获取属性值得时候,需要设置默认值,在用户没有设置本属性时,使用默认值。

private void init(Context context, AttributeSet attributeSet) { 

      if (attributeSet != null) { 

          TypedArray a = context.obtainStyledAttributes(attributeSet, R.styleable.RoundAngleImageView); 

          assert a != null; 

          roundWidth = a.getDimensionPixelSize(R.styleable.RoundAngleImageView_roundWidth, roundWidth); 

          roundHeight = a.getDimensionPixelSize(R.styleable.RoundAngleImageView_roundHeight, roundHeight); 

      } else { 

          float density = context.getResources().getDisplayMetrics().density; 

          roundWidth = (int) (roundWidth * density); 

          roundHeight = (int) (roundHeight * density); 

      } 


      paint = new Paint(); 

      paint.setColor(Color.WHITE); 

      paint.setAntiAlias(true); 

      paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.DST_OUT)); 


      paint2 = new Paint(); 

      paint2.setXfermode(null); 

      a.recycle();//为了保持以后使用的一致性,需要回收 

注意最后调用TypedArray的recycle方法。

以上三步,搞定。

参考:http://blog.csdn.net/caesardadi/article/details/20387645

二,Android 自定义主题和风格

样式和主题也是可以继承和引用的,类似于方法的引用。

样式的继承的格式:<style name="MyText" parent="@android:style/TextAppearance">   

引用的格式:  <item name="android:windowTitleStyle">@style/WindowTitle</item> 在某个style中的<item>中引用其他的style。

风格,也就是style,我们可以将一些统一的属性拿出来,比方说,长,宽,字体大小,字体颜色等等。

可以在res/values目录下新建一个styles.xml的文件,在这个文件里面有resource根节点,在根节点里面添加item项,item项的名字就是属性的名字,item项的值就是属性的值,如下所示:

<?xml version="1.0" encoding="utf-8"?>

<resources>

    <style name="MyText" parent="@android:style/TextAppearance">

        <item name="android:textColor">#987456</item>

        <item name="android:textSize">24sp</item>

    </style>

</resources>

style中有一个父类属性parent, 这个属性是说明当前的这个style是继承自那个style的

<EditText

      android:id="@+id/myEditText"

      android:layout_width="match_parent"

      android:layout_height="match_parent"

      style="@style/MyText"            //引用自定义的样式

      android:text="测试一下下"/>

说完了style,下面就说说Theme,

Theme跟style差不多,但是Theme是应用在Application或者Activity里面的,而Style是应用在某一个View里面的,还是有区别的。 //需要注意的地方

<?xml version="1.0" encoding="utf-8"?>

<resources>

    <style name="MyText" parent="@android:style/TextAppearance">

        <item name="android:textColor">#987456</item>

        <item name="android:textSize">24sp</item>

    </style>

    <style parent="@android:style/Theme" name="CustomTheme">

        <item name="android:windowNoTitle">true</item>

        <item name="android:windowFrame">@drawable/icon</item>

        <item name="android:windowBackground">?android:windowFrame</item>

    </style>

</resources>

可以看到这里写了一个继承自系统默认的Theme的主题,里面有3个属性,这里强调一下第三个属性的值的问题,

这里打个问号,然后加前面的一个item的名字表示引用的是那个名字的值,也就是那个名字对应的图片。

然后我们在Manifest.xml里面的Application里面加一个Theme的属性,这个属性对应的就是我们上面写的Them。

<application

android:icon="@drawable/icon"

android:label="@string/app_name"

android:theme="@style/CustomTheme"> //在Manifest.xml中引用自定义的主题

当然也可以在代码中设置主题:

@Override

    protected void onCreate (Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

     setTheme(R.style.CustomTheme); //在代码中引用自定义的主题

     setContentView(R.layout.test_style);

    }

尽管在定义上,样式和主题基本相同,但是它们使用的地方不同。样式用在单独的 View ,如: EditText 、TextView 等;主题通过 AndroidManifest.xml 中的 <application> 和 <activity> 用在整个应用或者某个 Activity,主题对整个应用或某个 Activity 进行全局性影响。如果一个应用使用了主题,同时应用下的 view 也使用了样式,那么当主题与样式属性发生冲突时,样式的优先级高于主题。

参考:http://www.cnblogs.com/shang53880/archive/2011/06/20/2085102.html

http://blog.csdn.net/piglite/article/details/46510745

三, 如何在android style文件中使用自定义属性

前几天我在项目中遇到了这样一个问题:我为项目编写了一个自定义控件,这个控件会被大量复用,所以我准备在style.xml文件中定义一个style来减少重复xml布局内容的编写,但是里面有一个自定义的控件属性,问题出现在这里,虽然自定义属性在layout布局xml中可以使用正常,但是却无法在style中定义,本来这个控件是大量服用的,style也是为了复用减少xml内容写的,我可以把自定义属性内容直接写死在自定义控件中,但是考虑到项目未来可能出现的变数,我还是准备将这个自定义属性写到style中,这样即便有其他不同样式的复用,我也只需再写一个style即可。

在layout布局中使用自定义属性是非常简单,我们只需要在xml根节点xmlns:Android="http://schemas.android.com/apk/res/android" 的后面加上我们自定义控件的命名空间(栗子:xmlns:test="http://schemas.android.com/apk/res/packagename),然后就可以在自定义控件节点里自由使用自定义属性了。

我在编写style的时候,起初也以为style.xml也应该是这种使用方式,于是就在根节点添加了自定义控件的命名空间,然后就在style中开始使用自定义属性,如下:

<resources xmlns:android="http://schemas.android.com/apk/res/android" 

    xmlns:test="http://schemas.android.com/res/com.zhufuing" > 

    <style name="test" > 

        <item name="test:name_text">hello,world!</item>       

    </style> 

</resources> 

但是这样并不起作用,style.xml反而出现错误,报错提示如下:

error: Error: No resource found that matches the given name: attr 'test:name_text'.

我在网上搜索之后得到了正确的答案,其实我们在style.xml中使用自定义属性的话,不需要写自定义控件的命名空间,我们只需要在style中使用命名控件的地方换成自定义控件的包名即可(注意:是包名,不带自定义控件的名字),如下:

<resources xmlns:android="http://schemas.android.com/apk/res/android" > 

    <style name="test" > 

        <item name="com.zhufuing:name_text">hello,world!</item>        //自定义控件的包名

    </style> 

</resources> 

这样就可以在style文件中使用自定义属性了。

参考:http://blog.csdn.net/dl6655/article/details/47334087

http://blog.csdn.net/waidazhengzhao/article/details/45771503    讲解的很全面详细

©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 194,242评论 5 459
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 81,769评论 2 371
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 141,484评论 0 319
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 52,133评论 1 263
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 61,007评论 4 355
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 46,080评论 1 272
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 36,496评论 3 381
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 35,190评论 0 253
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 39,464评论 1 290
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 34,549评论 2 309
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 36,330评论 1 326
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 32,205评论 3 312
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 37,567评论 3 298
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 28,889评论 0 17
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 30,160评论 1 250
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 41,475评论 2 341
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 40,650评论 2 335

推荐阅读更多精彩内容