Android使用AttributeSet自定义控件的方法

2020-03-21 12:09:59

参考地址 Android使用AttributeSet自定义控件的方法

当系统提供的控件,无法满足我们的需求的时候,我们往往会 想到自定义控件,通过继承View来实现。当我们想像 系统提供的控件那样可以如android:text="hello",这样设置自定义控件中的文字显示去,这时我们该怎么办?

带着问题,我们会想到在继承View的构造函数中 有个AttributeSet这个属性,没错  这就是 突破口。

我们可以在attrs.xml中声明自己控件的属性,在布局xml文档中声明自己的命名空间,这时就可以对设置自己想要的值了,然后在AttributeSet这个属性中获取对应的值。好了不多说,我们来看下代码,一切尽在不言中:

工程下载地址:点击打开链接

第一步:

在/res/values下编写一个attrs.xml的文件,其中内容结构如下:

    <?xml version="1.0" encoding="utf-8"?>
    <resources>
     
        <declare-styleable name="my_view">
            <attr name="text_color" format="color"></attr>
            <attr name="bg_color" format="color"></attr>
            <attr name="text" format="string"></attr>
        </declare-styleable>
     
    </resources>


其中要说的是format 格式,对于它的格式说明将在文章后面介绍。

第二步:

写一个自定义的Veiw,如下代码:

    public class myView extends View{
        private Paint paint;
        private int bg_color,text_color,alpha;
        private String text;
        public myView(Context context, AttributeSet attrs) {
            super(context, attrs);
            paint = new Paint();
            TypedArray s = context.obtainStyledAttributes(attrs, R.styleable.my_view);//从xml那传来的一组值
            bg_color = s.getColor(R.styleable.my_view_bg_color, R.color.transparent);//得到attrs中对应属性的bg_color值
            text_color = s.getColor(R.styleable.my_view_text_color, android.R.color.black);//..
            text = s.getText(R.styleable.my_view_text).toString();//..
     
        }
     
        @Override
        public void draw(Canvas canvas) {
            // TODO Auto-generated method stub
            super.draw(canvas);
            paint.setColor(bg_color);
            Rect r = new Rect(1, 80, 60, 140);
            canvas.drawRect(r, paint);
            paint.setColor(text_color);
            canvas.drawText(text, 10, 100, paint);
        }
    }


注释在重点地方已经写清楚了,也就值AttributeSet attrs 的使用,通过它可以获取在XML中定义的值。
第三步:

在布局文档中声明你的View

    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:app="http://schemas.android.com/apk/res/com.example.defineview"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:orientation="vertical" >
     
        <!-- 先声明命名空间 res/包名   以下就可以通过app:+attrs定义的属性,进行值设置 -->
        <com.example.defineview.myView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            app:text="nihao"
            app:text_color="#ff0000"
            app:bg_color="#00ff00"
             />
     
    </LinearLayout>

其中

xmlns:app="http://schemas.android.com/apk/res/com.example.defineview"

是自己声明的命名空间,app是头自由命名,在res/+自己的包名

这时你就可以使用

app:text="nihao"

这样的属性了,注意text、bg_color这些属性是在attrs中设置好的。

好了这样就OK了我们来看下运行效果:

运行效果中是不是显示出了

    app:text="nihao"
    app:text_color="#ff0000"
    app:bg_color="#00ff00"

的效果。

我们看下文件的目录结构



附录:attrs


在这里,需要补充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"

 

                     />

  • 2018-12-04 15:33:19

    CocoaPods安装和使用教程

    当你开发iOS应用时,会经常使用到很多第三方开源类库,比如JSONKit,AFNetWorking等等。可能某个类库又用到其他类库,所以要使用它,必须得另外下载其他类库,而其他类库又用到其他类库,“子子孙孙无穷尽也”,这也许是比较特殊的情况。总之小编的意思就是,手动一个个去下载所需类库十分麻烦。另外一种常见情况是,你项目中用到的类库有更新,你必须得重新下载新版本,重新加入到项目中,十分麻烦。如果能有什么工具能解决这些恼人的问题,那将“善莫大焉”。所以,你需要 CocoaPods。

  • 2018-12-04 23:37:37

    pod install 和 pod update

    当我们新建一个Podfile文件运行后,会自动生成一个Podfile.lock文件,Podfile.lock文件里存储着我们已经安装的依赖库(pods)的版本。 当我们第一次运行Podfile时,如果对依赖库不指定版本的话,cocoapods会安装最新的版本,同时将pods的版本记录在Podfile.lock文件中。这个文件会保持对每个pod已安装版本的跟踪,并且锁定这些版本。

  • 2018-12-04 23:40:26

    pod删除已导入的第三方库和移除项目中的cocoapods

    CocoaPods是一个负责管理iOS项目中第三方开源库的工具。CocoaPods的项目源码在Github上管理。在我们有了CocoaPods这个工具之后,只需要将用到的第三方开源库放到一个名为Podfile的文件中,然后在命令行执行$ pod install命令。CocoaPods就会自动将这些第三方开源库的源码下载下来,并且为我的工程设置好相应的系统依赖和编译参数. 但是如果我们导入的某个第三方不适用,或者我们又不想使用该第三方,那我们又该如何将这些相关的东西从我们的项目中清理出去呢?

  • 2018-12-04 23:41:47

    制作自己的Pod库(公有/私有)

    目的:1.管理自己常用的类;2.组件化开发步骤:1.想一个比较酷的名字,在桌面简历文件夹。2.打开terminal,cd到这个文件夹下面,执行pod lib create  xxx(这里我们以JJCategoryKit为例子,下同)命令,如下图。这个过程会问几个问题,根据实际情况输入回答即可。这里我们选择添加demo,结束的时候会自动Lanuch这个app. 作者:深水日月 链接:https://www.jianshu.com/p/ece0b5721461 來源:简书 简书著作权归作者所有,任何形式的转载都请联系作者获得授权并注明出处。

  • 2018-12-05 06:08:26

    CocoaPods建立私有仓库 spec repo

    好多项目里都有公共的组件,copy来,copy去很容易出错,而且不容易维护,所以就想到用用cocoapods 建自己的私有库,Carthage用法虽然相对简单,但是它是把公共组件都放在framework里不容易单步调试,所以我还是选择用Cocoapods 来建立私有仓库 参考使用Cocoapods创建私有podspec

  • 2018-12-05 15:11:18

    为什么 Objective-C非常难

    作为一个Objective-C的coder,我总能听到一部 分人在这门语言上抱怨有很多问题。他们总在想快速学习这门语言来写一个App出来,但他们也总是联想到Objective-C看上去实在太难了或者在想这 些语法符号都是神马玩意?不错,他们问得非常好,所以本人也解释一下为什么很多程序员相比较学习Ruby或者Java很容易,但在决定开发iOS或者OS X应用时会那么犹豫。

  • 2018-12-05 15:22:23

    十分钟让你明白Objective-C的语法(和Java、C++的对比)

    很多想开发iOS,或者正在开发iOS的程序员以前都做过Java或者C++,当第一次看到Objective-C的代码时都会头疼,Objective-C的代码在语法上和Java, C++有着很大的区别,有的同学会感觉像是看天书一样。不过,语言都是相通的,有很多共性。下面列出Objective-C语言的语法和Java,C++的对比,这样你就会很容易Objective-C的语法是怎么回事了。

  • 2018-12-05 15:33:33

    一篇文章看懂有关iOS开发语言的一切!

    OS开发语言有哪些?OS开发语言主要包括什么?iOS开发语言具体怎么学习?今天重点介绍一下: iOS开发语言主要包括:C语言基础、Obiective-C编程、Swift、UIKit框架详解这几大块,在这里项目阶段就不详细的介绍了。 C语言基础 C语言是开发语言的基础,是最常用的一门程序设计语言,最常用于编写计算机程序。

  • 2018-12-06 10:03:36

    定时杀掉processlist sleep状态的线程

    由于程序设计的Bug,导致目前这个项目使用的数据库中有很多Sleep状态的线程。找了很多解决办法,还没发现最终有效的解决方案。只能临时使用如下方法: 编写shell文件,如killSleepProcess.sh