自定义View或者ViewGroup的自定义属性使用技巧

首先在/res/values文件夹下新建一个attrs.xml文件(这里文件名可随意起,但约定俗成用attrs)

attrs.xml

<?xml version="1.0" encoding="utf-8"?>
<resources>
    
        <declare-styleable name = "ViewPagerIndicator">
            <attr name = "visible_tab_count" format = "integer"/>
            <attr name = "title_text" format = "String"/>
            <attr name = "title_color" format = "color"/>
        </declare-styleable>
            
    
</resources>

在自定义View的初始化过程中取得相关属性,这里以visible_tab_count属性为例。

TypedArray a = context.obtainStyledAttributes(attrs,R.styleable.ViewPagerIndicator);
		mTabVisibleCount = a.getInt(R.styleable.ViewPagerIndicator_visible_tab_count, COUNT_DEFAULT_TAB);
		if(mTabVisibleCount<0){
			mTabVisibleCount = COUNT_DEFAULT_TAB;
		}
		a.recycle();

在XML布局文件中使用此自定义属性,首先在根布局中声明命名空间,然后在自定义view中使用该属性

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    xmlns:zhu = "http://schemas.android.com/apk/res/com.example.viewpagerindicator"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#ffffffff"
    android:orientation="vertical" >

    <com.example.viewpagerindicator.ViewPagerIndicator 
        android:layout_width="match_parent"
        android:layout_height="40dp"
        zhu:visible_tab_count = "4"
        android:background="@drawable/editor_titlebar_background"
        android:orientation="horizontal"
        android:id="@+id/ViewPagerIncator">
       
    </com.example.viewpagerindicator.ViewPagerIndicator>
    
</LinearLayout>
 xmlns:zhu = "http://schemas.android.com/apk/res/com.example.viewpagerindicator"是命名空间,固定的组成格式:http://schemas.android.com/apk/res/+包名

zhu:visible_tab_count = "4"  自定义View使用自定义属性


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值