Android组合控件是自定义控件的一种,只不过它是由其他几个原生控件组合而成,故名组合控件。在实际项目中,GUI会遇到一些可以提取出来做成自定义控件情况。一个自定义控件的好处就是把一些需要模块化的UI和逻辑放在一起,做到了高内聚,向其他模块提供接口并很少
依赖外界,这样就是低耦合。一个自定义控件就是一个封闭的王国,这里由你掌控。
上述是我自己的一个体会,想必大家也会常做自定义控件吧,就像逻辑部分的模块化一样。
更多Android相关信息见Android 专题页面 http://www.linuxidc.com/topicnews.aspx?tid=11下面我要做一个例子,请看完成图。
下面一排图片加文字就是组合控件了,我是怎么做的呢?其实这里用到了两个组合控件,一个是图片+文字,我把它叫一个Item,而三个在一起就是另一个控件了。重点看这个Item,它有自己的属性如图片、文字、图片大小、文字大小、不透明度等等。这些把它定义在attr文件中,然后在xml文件中配置,就像我们用原生控件一样。先看attr文件。
- <?xml version="1.0" encoding="utf-8"?>
- <resources>
- <declare-styleable name="LevelMenuItem">
- <attr name="text" format="string" />
- <attr name="text_color" format="color"/>
- <attr name="text_size" format="dimension" />
- <attr name="image_src" format="reference"/>
- <attr name="image_bg" format="reference"/>
- <attr name="image_alpha" format="integer" />
- <attr name="image_height" format="dimension"></attr>
- <attr name="image_width" format="dimension" />
- </declare-styleable>
- </resources>
这个文件在values下,和string文件同级。把你自己要定义的属性都写在这里吧。format是属性的“单位”,如果你要问有多少中format呀?答案在
这里。
有了属性了,下面看看布局文件level_menu_item.xml。
- <?xml version="1.0" encoding="utf-8"?>
- <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
- android:layout_width="fill_parent"
- android:layout_height="fill_parent"
- android:orientation="vertical" >
- <ImageView
- android:id="@+id/image_item"
- android:layout_width="fill_parent"
- android:layout_height="fill_parent"
- android:scaleType="fitCenter"
- />
- <TextView
- android:id="@+id/tv_item"
- android:layout_width="fill_parent"
- android:layout_height="wrap_content"
- android:gravity="center_horizontal"
- android:textColor="#23ffffff"
- android:textSize="25sp"
- />
- </LinearLayout>
这里唯一值得一说的是文本的颜色。大家看见他是8位的,前两位是表示不透明度的,后六位是表示颜色的,三色,范围都是00~ff。 如果在java中设置颜色,需要这样。
- setTextColor(0x23ffffff);
关于不透明度,一般美工会定义。有些要求不透明如30%这样的,可以用整型换算一下。00~ff对应十进制为0~255,那么30%就是255x0.3=76.5,用科学计算机换算为4c。更多颜色相关请看《Android中设置文本颜色的三种办法》见 http://www.linuxidc.com/Linux/2012-04/58697.htm