android 自定义组件,使用AttributeSet

2020-03-21 12:05:24

参考地址 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效果。

  • 2018-08-14 23:35:28

    Retrofit 设置 超时时间

    今天开发的时候遇到一个网络请求超时的问题,后台处理是成功的,但是移动端返回的总是提示请求超时,在设置了retrofit请求超时的时间延长以后,就可以请求成功了,下面是配置的方法:

  • 2018-08-16 16:10:43

    Laravel 跨域解决方案

    我们在用 laravel 进行开发的时候,特别是前后端完全分离的时候,由于前端项目运行在自己机器的指定端口(也可能是其他人的机器) , 例如 localhost:8000 , 而 laravel 程序又运行在另一个端口,这样就跨域了,而由于浏览器的同源策略,跨域请求是非法的。其实这个问题很好解决,只需要添加一个中间件就可以了。

  • 2018-08-18 20:30:12

    laravel5.5 路由分割成不同文件

    routes.php/api.php文件用来放置laravel路由,当项目越来越大,相应的路由文件也会越来越多。如果能够将不同功能的路由分割到不同的文件,那么对以后的维护将很有帮助。

  • 2018-08-20 15:26:19

    关于OnTouch 和OnClick同时调用冲突的解决方案

    大家在搞轮播图的时候会碰到这样的情况,点击进入webview界面,长按轮播图停止轮播,手松开图又开始轮播,这里就涉及到了OnTouch 和OnClick同时调用。两者是有冲突的。这里简单介绍,给大家提供思路。

  • 2018-08-20 15:29:11

    揭开RecyclerView的神秘面纱(二):处理RecyclerView的点击事件

    主要讲述了RecyclerView的基本使用方法,不同的布局管理器而造成的多样化展示方式,展示了数据之后,一般都会与用户进行交互,因此我们需要处理用户的点击事件。在ListView和GridView提供了onItemClickListener这个监听器,然而我们查找RecyclerView的API却没有类似的监听器,因此我们需要自己手动处理它的点击事件。 以下提供两种方法来实现处理RecyclerView点击事件的功能,以下代码均基于上一篇文章的代码做出修改。

  • 2018-08-20 22:58:46

    onInterceptTouchEvent和onTouchEvent调用关系详解 ...

    老实说,这两个小东东实在是太麻烦了,很不好懂,我自己那api文档都头晕,在网上找到很多资料,才知道是怎么回事,这里总结一下,记住这个原则就会很清楚了:

  • 2018-08-23 15:32:18

    map对象拷贝问题

    最后面是使用序列化的方式,发现,更改引用类型的数据的时候,mapNew对象并没有发生变化,所以产生了深拷贝。 上述的工具类,可以实现对象的深拷贝,不仅限于HashMap,前提是实现了Serlizeable接口。

  • 2018-08-24 11:33:17

    总结和分析几种判断 RecyclerView 到达底部的方法

    SwipeRefreshLayout 写一个 RecyclerView 的上下拉 ,里面有一个判断 RecyclerView 是否到达底部的方法 isBottom。我的同事用了这个上下拉之后发现有些小 bug,没考虑周全,譬如各个子项高度不统一的时候,然后我找到原因是因为这个判断上下拉的问题。所以,我就去网上查到几种判断 RecyclerView 到达底部的方法,发现各有千秋。以下的分析都以上一篇文章的 SwipeRecyclerView 为例