android 自定义View 之自定义属性

1:新建 attrs文件 目录 res/value/attrs.xml 

 属性类型一共有8种:string,color,demension,integer,enum,reference,float,boolean,fraction,flag;

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

<resources>

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

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

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

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

    <attr name="imageScaleType">

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

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

    </attr>

    <declare-styleable name="CustomView">

        <attr name="titleText" />

        <attr name="titleTextSize" />

        <attr name="titleTextColor" />

        <attr name="image" />

        <attr name="imageScaleType" />

    </declare-styleable>

</resources>


2:布局中使用:

一定要引入 xmlns:custom="http://schemas.android.com/apk/res/com.example.customview01"我们的命名空间,后面的包路径指的是项目的package  或者  xmlns:custom="http://schemas.android.com/apk/res-auto"

xmlns的作用

xml布局中使用最多的是android:id、andorid:layout_width等形式,在我们自定义的xml中,添加了app:Text、app:TextAllow等这样的写法,其实冒号前面的单词并不重要,重要的是后面引号中的内容,前面的单词可以任意取名,我们在最开始指定了这样一句代码:

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

包括系统自动为我们添加的这一句代码:

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

正是这两句代码的存在,才使得我们能够使用android、app这样的标签,为什么呢?


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

    xmlns:tools="http://schemas.android.com/tools"

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

    android:layout_width="match_parent"

    android:layout_height="match_parent"

    android:orientation="vertical" >

<--或者声明这个-->

<-- xmlns:custom="http://schemas.android.com/apk/res-auto"-->

    <com.zhy.customview02.view.CustomImageView

        android:layout_width="wrap_content"

        android:layout_height="wrap_content"

        android:layout_margin="10dp"

        android:padding="10dp"

        custom:image="@drawable/ic_launcher"

        custom:imageScaleType="center"

        custom:titleText="hello andorid ! "

        custom:titleTextColor="#ff0000"

        custom:titleTextSize="30sp" />

</LinearLayout>


3:自定义view中使用

public class CustomView extends View {

    public CustomView(Context context, AttributeSet attrs) {

        super(context, attrs);

        TypedArray ta = context.obtainStyledAttributes(attrs,

                      R.styleable.CustomView);

        String text = ta.getString(R.styleable.CustomeView_titletext);

        Bitmap mImage = BitmapFactory.decodeResource(getResources(),

                    ta.getResourceId(R.styleable.CustomeView_image, 0));

        int  mTextSize =

              ta.getDimensionPixelSize(R.styleable.CustomeView_titleTextSize, (int)

              TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP,

16, getResources().getDisplayMetrics()));

        ta.recycle();

    }

    public CustomView(Context context,AttributeSet attrs,int defStyleAttr){

        super(context, attrs,defStyleAttr);

    TypedArray typedArray =context.getTheme().obtainStyledAttributes(attrs,

                            R.styleable.CustomView,defStyleAttr,0);

  }

}

4:TypedArray和AttributeSet的不同

AttributeSet中的确保存的是该View声明的所有的属性,并且外面的确可以通过它去获取属性自定义和原有的属性

public CustomView(Context context, AttributeSet attrs) {

        super(context, attrs);

        int count = attrs.getAttributeCount();

        for (int i = 0; i < count; i++) {

            String attrName = attrs.getAttributeName(i);

            String attrVal = attrs.getAttributeValue(i);

            Log.e(TAG, "attrName = " + attrName + " , attrVal = " + attrVal);

        }

    }


通过AttributeSet可以获得布局文件中定义的所有属性的key和value,但通过AttributeSet获取的值,如果是值是@的资源,那么引用都变成了@+数字的字符串。

ypedArray其实是用来简化我们的工作的,比如上例,如果布局中的属性的值是引用类型(比如:@dimen/dp100),如果使用AttributeSet去获得最终的像素值,那么需要第一步拿到id,第二步再去解析id。而TypedArray正是帮我们简化了这个过程。

贴一下:如果通过AttributeSet获取最终的像素值的过程:

int widthDimensionId =  attrs.getAttributeResourceValue(0, -1);

        Log.e(TAG, "layout_width= "+getResources().getDimension(widthDimensionId));

5:declare-styleable

直接在attrs.xml中使用android:text属性。


  <declare-styleable name="test">

        <attr name="android:text" />

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

    </declare-styleable>

注意,这里我们是使用已经定义好的属性,不需要去添加format属性(注意声明和使用的区别,差别就是有没有format)。 

然后在类中这么获取:ta.getString(R.styleable.test_android_text);布局文件中直接android:text="@string/hello_world"即可。

declare-styleable的标签也可以不写

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

<resources>

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

</resources>

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

<resources>

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

</resources>


public class MyTextView extends View {

    private static final String TAG = MyTextView.class.getSimpleName();

    private static final int[] mAttr = { android.R.attr.text, R.attr.testAttr };

    private static final int ATTR_ANDROID_TEXT = 0;

    private static final int ATTR_TESTATTR = 1;

    public MyTextView(Context context, AttributeSet attrs) {

        super(context, attrs);

        // ==>use typedarray

        TypedArray ta = context.obtainStyledAttributes(attrs, mAttr);

        String text = ta.getString(ATTR_ANDROID_TEXT);

        int textAttr = ta.getInteger(ATTR_TESTATTR, -1);

        //输出 text = Hello world! , textAttr = 520

        Log.e(TAG, "text = " + text + " , textAttr = " + textAttr);

        ta.recycle();

    }

}


可以看到我们声明了一个int数组,数组中的元素就是我们想要获取的attr的id。并且我们根据元素的在数组中的位置,定义了一些整形的常量代表其下标,然后通过TypedArray进行获取。

https://blog.csdn.net/lmj623565791/article/details/45022631

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

推荐阅读更多精彩内容