Welcome 微信登录
编程资源 图片资源库 蚂蚁家优选 PDF转换器

首页 / 操作系统 / Linux / Android实战技巧之组合控件

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