Android自定义View——自定义属性attrs.xml的使用


1、attrs.xml 的作用

使用attrs.xml文件,可以自己定义属性


2、在values文件夹下,新建一个attrs.xml文件


<?xml version="1.0" encoding="utf-8"?>
<declare-styleable name="MyView">
        <attr name="textColor" format="color" />
        <attr name="textSize" format="dimension" />
 </declare-styleable>
 

其中,

<declare-styleable name="MyView">

表明样式名称为 MyView ,下面包含了两个自定义属性 textColortextSize ,其中textColor是颜色(color)类的属性,textSize是尺寸(dimension)类的属性


3、自定义 MyView

public class MyView extends View {

    private Paint mPaint;
    private static final String mString = "Welcome to BaiYe's blog";

    public MyView(Context context) {
        this(context,null);
    }

    public MyView(Context context, AttributeSet attrs) {
        super(context, attrs);
        mPaint = new Paint();

		//TypedArray是一个数组容器
        TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.MyView);
        //这里的属性是:名字_属性名
        int textColor = a.getColor(R.styleable.MyView_textColor, 0XFFFFFFFF);
        //防止在XML文件里没有定义,就加上了默认值36
        float textSize = a.getDimension(R.styleable.MyView_textSize, 36);

        mPaint.setTextSize(textSize);
        mPaint.setColor(textColor);
        a.recycle();//我的理解是:返回以前取回的属性,供以后使用。以前取回的可能就是textSize和textColor初始化的那段 
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        // 设置填充
        mPaint.setStyle(Paint.Style.FILL);
        // 画一个矩形,前俩个是矩形左上角坐标,后面俩个是右下角坐标
//        mPaint.setColor(Color.BLACK);
        canvas.drawRect(new Rect(10, 10, 100, 100), mPaint);
        // 绘制文字
        canvas.drawText(mString, 60, 410, mPaint);
    }
}


4、xml 布局内容:使用自定义的MyView

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    xmlns:test="http://schemas.android.com/apk/res-auto"//一定记得添加前缀 
    android:id="@+id/activity_attrs_actiity"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.lizi.newset.CustomView.attrs.AttrsActivity">

    <com.lizi.newset.CustomView.attrs.MyView
        android:id="@+id/myView"
        android:layout_height="match_parent"
        android:layout_width="wrap_content"
        test:textSize="50px"
        test:textColor="#ff00ff"/>
    />
</RelativeLayout>

5、自定义属性

5.1、reference:参考某一资源ID


<declare-styleable name = "名称">
      <attr name = "background" format = "reference" />
</declare-styleable>

eg:

<ImageView
     android:layout_width = "42dip"
     android:layout_height = "42dip"
     android:background = "@drawable/图片ID"
                     />

5.2、color:颜色值


<declare-styleable name = "名称">
       <attr name = "textColor" format = "color" />
</declare-styleable>

eg:


 <TextView
     android:layout_width = "42dip"
     android:layout_height = "42dip"
     android:textColor = "#00FF00"
                     />

5.3、boolean:布尔值


<declare-styleable name = "名称">
      <attr name = "focusable" format = "boolean" />
</declare-styleable>

eg:


<Button
    android:layout_width = "42dip"
    android:layout_height = "42dip"
    android:focusable = "true"/>

5.4、dimension:尺寸值


<declare-styleable name = "名称">
     <attr name = "layout_width" format = "dimension" />
</declare-styleable>

eg:

<com.lizi.newset.CustomView.attrs.MyView
        android:id="@+id/myView"
        android:layout_height="match_parent"
        android:layout_width="wrap_content"
        test:textSize="50px"
        test:textColor="#ff00ff"/>

5.5、float:浮点值


<declare-styleable name = "AlphaAnimation">
      <attr name = "fromAlpha" format = "float" />
      <attr name = "toAlpha" format = "float" />
</declare-styleable>

eg:


<alpha
       android:fromAlpha = "1.0"
       android:toAlpha = "0.7"
/>

5.6、string:字符串


<declare-styleable name = "MapView">
     <attr name = "apiKey" format = "string" />
</declare-styleable>

eg:


<com.google.android.maps.MapView
         android:layout_width = "fill_parent"
         android:layout_height = "fill_parent"
         android:apiKey = "0jOkQ80oD1JL9C6HAja99uGXCRiS2CGjKO_bc_g"
                    />

5.7、integer:整型值 || fraction:百分数


<declare-styleable name = "AnimatedRotateDrawable">
      <attr name = "visible" />
      <attr name = "frameDuration" format="integer" />
      <attr name = "framesCount" format="integer" />
      <attr name = "pivotX"  format = "fraction"/>
      <attr name = "pivotY"  format = "fraction"/>
      <attr name = "drawable" />
</declare-styleable>

eg:


<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"
  />

5.8、enum:枚举值


<declare-styleable name="名称">
    <attr name="orientation">
    	<enum name="horizontal" value="0" />
        <enum name="vertical" value="1" />
    </attr>                           
</declare-styleable>

eg:


<LinearLayout
	xmlns:android = "http://schemas.android.com/apk/res/android"
    android:orientation = "vertical"
    android:layout_width = "fill_parent"
    android:layout_height = "fill_parent">
</LinearLayout>

5.9、flag 位或运算


 <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>

eg:


<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>

6、属性定义时可以同时定义多种类型值


<declare-styleable name = "名称">
      <attr name = "background" format = "reference|color" />
</declare-styleable>

eg:


<ImageView
        android:layout_width = "42dip"
        android:layout_height = "42dip"
        android:background = "@drawable/图片ID|#00FF00"
        />

7、参考文章

Android中attrs.xml文件的使用详解
Android中自定义属性(attrs.xml,TypedArray的使用)

Android 开发中,attrs.xml 是一个非常重要的文件,它用于定义自定义属性,可以让我们在布局文件中直接使用这些属性。 下面是一个示例 attrs.xml 文件: ```xml <?xml version="1.0" encoding="utf-8"?> <resources> <attr name="myText" format="string" /> <attr name="myTextColor" format="color" /> <attr name="myBackgroundColor" format="color" /> </resources> ``` 这个文件定义了三个自定义属性:myText、myTextColor 和 myBackgroundColor。其中,name 属性指定属性的名称,format 属性指定属性的类型。 在布局文件中使用自定义属性的方法是: ```xml <com.example.MyView android:layout_width="match_parent" android:layout_height="wrap_content" app:myText="Hello World!" app:myTextColor="@color/red" app:myBackgroundColor="@color/white" /> ``` 在 MyView 类中,可以通过如下方法获取这些自定义属性的值: ```java TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.MyView); String myText = a.getString(R.styleable.MyView_myText); int myTextColor = a.getColor(R.styleable.MyView_myTextColor, Color.BLACK); int myBackgroundColor = a.getColor(R.styleable.MyView_myBackgroundColor, Color.WHITE); a.recycle(); ``` 其中,obtainStyledAttributes() 方法获取了这些属性的值,getString() 和 getColor() 方法获取了对应属性的值,recycle() 方法回收 TypedArray 对象。 通过自定义属性,我们可以让布局文件更加简洁明了,代码也更加易于维护。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值