Android高手进阶篇2-自定义AttributeSet属性

    前段时间因为项目的需求,而需要自定义控件的AttributeSet属性,那么我们什么时候需要这种方法来自定义控件呢?好了,不卖关子啦,直接进入主题,一般是当项目中遇到这样的场景需要自定义控件的AttributeSet属性:一个自定义控件的有些属性内容是随着外部条件而动态改变的,for example:一个自定义的ListView控件,需要在底部添加一个View,而这个View在不同的模块使用中传入的View是不同的,这时候有两种方法,一种方法就是在自定义ListView控件类中提供一个公开的接口给外部调用从而将View动态的传入进去;另外一种方法就是在通过自定义控件属性,直接类似于系统属性如Android:textsize 的用法 app:boottomView; 通过第二种方法自定义控件在XML中使用时和系统控件的属性使用方法一样,很简单、方便,而且动态、灵活、更具模块框架化,其属性内容直接在xml中动态配置,不了解其原理的人也能将该控件整合到自己的项目中快速使用起来。

  自定义控件的AttributeSet属性步骤大致如下:

一、 首先要在res/values目录下建立一个attrs.xml(名字可以自己定义)的文件,并在此文件中增加对控件的属性的定义.其xml文件如下所示:

<?xml version="1.0" encoding="utf-8"?>
<resources>
   <declare-styleable name="my_text_view">
       <attr name="text_size" format="float"></attr>
       <attr name="text_color" format="color"></attr>
       <attr name="text_back_ground" format="color|reference"></attr>

   </declare-styleable>
</resources>

在这里,需要补充attrs属性的相关知识,即Attr属性是如何在XML中定义的,自定义属性的Value值可以有10种类型以及其类型的组合值,其具体使用方法如下:

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的类,其中下面的构造方法是重点,在代码中获取自定义属性,其代码如下:

package com.example.CustomAttr;

import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Paint;
import android.util.AttributeSet;
import android.util.TypedValue;
import android.widget.TextView;

/**
 * Created with IntelliJ IDEA.
 * User: zhiwen.nan
 * Date: 13-9-28
 * Time: 下午10:00
 * To change this template use File | Settings | File Templates.
 */
public class CustomTextView extends TextView {
    private TypedArray mTypedArray;
    private Paint mPaint;

    public CustomTextView(Context context) {
        super(context);
    }

    public CustomTextView(Context context, AttributeSet attrs) {
        super(context, attrs);
        inial(context,attrs);
    }

    public CustomTextView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        inial(context,attrs);
    }

    private void inial(Context context,AttributeSet attrs)  {
        TypedArray typedArray = context.obtainStyledAttributes(attrs,R.styleable.my_text_view);

        float textsize = typedArray.getFloat(R.styleable.my_text_view_text_size,14)   ;
        int textColor = typedArray.getColor(R.styleable.my_text_view_text_color,0xFFFFFF)   ;
        int bgColor = typedArray.getColor(R.styleable.my_text_view_text_back_ground,0xFFFFFF) ;

        super.setTextColor(textColor);
        super.setTextSize(textsize);
        super.setBackgroundColor(bgColor);


        typedArray.recycle();

    }



}


三、接下来在XML布局中引用自定义View控件,其XML代码如下:

?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
                xmlns:app = "http://schemas.android.com/apk/res/com.example.CustomAttr"
              android:orientation="vertical"
              android:layout_width="fill_parent"
              android:layout_height="fill_parent"
        >

    <com.example.CustomAttr.CustomTextView
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:text="Hello World, MainActivity"
            app:text_size ="20"
            app:text_color ="#00FF00"
            app:text_back_ground="#ffffff"

            />
</LinearLayout>


注意上面XML中代码:   xmlns:app = "http://schemas.android.com/apk/res/com.example.CustomAttr",是自定义的app命名空间,res后面是应用程序包名,然后可以直接使用app:text_size,等属性,其值类型要和attrs.xml定义的属性Value值相对应。

四、总结:

    注意该例子中是使用app:text_size = "20 和app:text_color="#00FF00定义TextView的颜色和textView的字体大小,而不是使用系统的属性android:textsize等。该例子中只是起到抛砖引玉的作用,你可以自定义其他属性,来实现你想要的自定义View效果。

例子资源下载:  http://download.csdn.net/detail/nanzhiwen666/6346979


  • 10
    点赞
  • 25
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 2
    评论
实现圆弧进度条的自定义ProgressBar,可以使用Canvas和Paint来绘制。 首先,创建一个自定义的ProgressBar类,继承自ProgressBar类,并实现构造方法和onDraw方法: ``` public class CircleProgressBar extends ProgressBar { private Paint paint; // 画笔 private int roundColor; // 圆环颜色 private int progressColor; // 进度条颜色 private int textColor; // 文字颜色 private float textSize; // 文字大小 private float roundWidth; // 圆环宽度 private int max; // 最大进度 private boolean textIsDisplayable; // 是否显示进度文字 private int style; // 进度条样式 public static final int STROKE = 0; public static final int FILL = 1; public CircleProgressBar(Context context) { this(context, null); } public CircleProgressBar(Context context, AttributeSet attrs) { this(context, attrs, 0); } public CircleProgressBar(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); // 获取自定义属性的值 TypedArray mTypedArray = context.obtainStyledAttributes(attrs, R.styleable.CircleProgressBar); roundColor = mTypedArray.getColor(R.styleable.CircleProgressBar_roundColor, Color.RED); progressColor = mTypedArray.getColor(R.styleable.CircleProgressBar_progressColor, Color.GREEN); textColor = mTypedArray.getColor(R.styleable.CircleProgressBar_textColor, Color.GREEN); textSize = mTypedArray.getDimension(R.styleable.CircleProgressBar_textSize, 15); roundWidth = mTypedArray.getDimension(R.styleable.CircleProgressBar_roundWidth, 5); max = mTypedArray.getInteger(R.styleable.CircleProgressBar_max, 100); textIsDisplayable = mTypedArray.getBoolean(R.styleable.CircleProgressBar_textIsDisplayable, true); style = mTypedArray.getInt(R.styleable.CircleProgressBar_style, 0); mTypedArray.recycle(); // 初始化画笔 paint = new Paint(); } @Override protected synchronized void onDraw(Canvas canvas) { super.onDraw(canvas); // 获取圆心坐标和半径 int centerX = getWidth() / 2; int centerY = getHeight() / 2; int radius = (int) (centerX - roundWidth / 2); // 绘制圆环 paint.setColor(roundColor); paint.setStyle(Paint.Style.STROKE); paint.setStrokeWidth(roundWidth); paint.setAntiAlias(true); canvas.drawCircle(centerX, centerY, radius, paint); // 绘制进度条 paint.setStrokeWidth(roundWidth); paint.setColor(progressColor); RectF oval = new RectF(centerX - radius, centerY - radius, centerX + radius, centerY + radius); switch (style) { case STROKE: paint.setStyle(Paint.Style.STROKE); canvas.drawArc(oval, 0, 360 * getProgress() / getMax(), false, paint); break; case FILL: paint.setStyle(Paint.Style.FILL_AND_STROKE); if (getProgress() != 0) canvas.drawArc(oval, 0, 360 * getProgress() / getMax(), true, paint); break; } // 绘制文字 paint.setStrokeWidth(0); paint.setColor(textColor); paint.setTextSize(textSize); paint.setTypeface(Typeface.DEFAULT_BOLD); int percent = (int) (((float) getProgress() / (float) getMax()) * 100); if (textIsDisplayable && percent >= 0) { String text = percent + "%"; float textWidth = paint.measureText(text); canvas.drawText(text, centerX - textWidth / 2, centerY + textSize / 2, paint); } } } ``` 在这个类中,我们定义了几个自定义属性,包括圆环颜色、进度条颜色、文字颜色、文字大小、圆环宽度、最大进度、是否显示进度文字、进度条样式等。在构造方法中,我们获取了这些属性的值,并初始化了画笔。在onDraw方法中,我们首先获取了圆心坐标和半径,然后使用画笔绘制了圆环和进度条,最后绘制了进度文字。 接下来,在布局文件中使用这个自定义ProgressBar: ``` <com.example.circleprogressbar.CircleProgressBar android:id="@+id/circle_progressbar" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerInParent="true" app:roundColor="#cccccc" app:roundWidth="5dp" app:progressColor="#FF4081" app:textColor="#FF4081" app:textSize="20sp" app:textIsDisplayable="true" app:style="STROKE" /> ``` 最后,在Java代码中设置进度值即可: ``` CircleProgressBar circleProgressBar = findViewById(R.id.circle_progressbar); circleProgressBar.setProgress(50); // 设置进度为50% ``` 这样就完成了自定义的圆弧进度条的实现。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

我心飞翔.坚定不移

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值