自定义属性 attr

来源:互联网 发布:淘宝店铺文案怎么写 编辑:程序博客网 时间:2024/05/16 07:43
自定义属性步骤:
第一步在attrs.xml定义
<?xml version="1.0" encoding="UTF-8"?>
<resources>
<declare-styleable name="gifView">
<!--图片来源-->
<attr name="src" format="integer" />


<!-- 播放延迟 -->
<attr name="delay" format="integer" />




<!-- 设置是否停止  -->
<attr name="stop" format="boolean" />
</declare-styleable>
</resources>


第二步:
在代码中使用
                  TypedArray ta = context.obtainStyledAttributes(attrs,
R.styleable.gifView);//取出属性的子集
              int n = ta.getIndexCount();//子集的个数


for (int i = 0; i < n; i++) {
int attr = ta.getIndex(i);


switch (attr) {
case R.styleable.gifView_src:
//获取该属性对应的id  gif:src="@raw/f"  


int id = ta.getResourceId(R.styleable.gifView_src, 0);

setSrc(id);
break;
//gif:delay="1"
case R.styleable.gifView_delay:
int idelta = ta.getInteger(R.styleable.gifView_delay, 1);
setDelta(idelta);
break;
//gif:stop="true" 
case R.styleable.gifView_stop:
boolean sp = ta.getBoolean(R.styleable.gifView_stop, false);
if (!sp) {
setStop();
}

break;
}


}


在xml中  xmlns:gif="http://schemas.android.com/apk/res/包名"
<com.terry.gif.TypegifView
   android:layout_centerHorizontal="true"
   android:layout_centerVertical="true"
android:layout_width="wrap_content"
android:id="@+id/gifView1"
android:layout_height="wrap_content"
gif:stop="true" 
gif:src="@raw/f"
gif:delay="1"
>
   
</com.terry.gif.TypegifView>

0 0
原创粉丝点击