android中的color使用总结

来源:互联网 发布:怎么维护代理商 知乎 编辑:程序博客网 时间:2024/05/18 14:42

在android开发中,适当的颜色搭配可以为我们的应用增色不少,废话就不多了,一下是对

android开发中颜色使用的总结



颜色分类:


1.系统颜色

android内置的颜色,比如系统资源中定义的颜色,有以下几个:

BLACK(黑色),BLUE(蓝色),CYAN(青色),GRAY(灰色),GREEN(绿色),RED(红色),WRITE(白色),YELLOW(黄色)等

当然android的android.graphics.Color也提供了构造自定义颜色的静态方法


系统颜色的使用

①在Java代码直接设置

[java] view plaincopyprint?在CODE上查看代码片派生到我的代码片
  1. <span style="font-family:Comic Sans MS;">Button btn = (Button) findViewById(R.id.btn);  
  2.         btn.setBackgroundColor(Color.BLUE);</span>  

当然你也可以获取系统颜色后再设置:

[java] view plaincopyprint?在CODE上查看代码片派生到我的代码片
  1. <span style="font-family:Comic Sans MS;">int getcolor = Resources.getSystem().getColor(android.R.color.holo_green_light);  
  2.         Button btn = (Button) findViewById(R.id.btn);  
  3.         btn.setBackgroundColor(getcolor);</span>  



②在布局文件中使用

[html] view plaincopyprint?在CODE上查看代码片派生到我的代码片
  1. <span style="font-family:Comic Sans MS;"><Button  
  2.         android:id="@+id/btn"  
  3.         android:background="@android:color/black"  
  4.         android:layout_width="wrap_content"  
  5.         android:layout_height="wrap_content"  
  6.         android:text="按钮" /></span>  


2.自定义颜色

颜色值的定义是由透明度alphaRGB(红绿蓝)三原色来定义的,
“#”开始,后面依次为:透明度-红-绿-蓝

eg:#RGB    #ARGB  #RRGGBB  #AARRGGBB   

而我们最常使用的就是后面两种

自定义颜色的使用:


①直接在xml文件中使用:

[html] view plaincopyprint?在CODE上查看代码片派生到我的代码片
  1. <span style="font-family:Comic Sans MS;"><Button  
  2.         android:id="@+id/btn"  
  3.         android:background="#874516"  
  4.         android:layout_width="wrap_content"  
  5.         android:layout_height="wrap_content"  
  6.         android:text="按钮" /></span>  

当然你也可以在res/values目录下,新建一个color.xml文件,为你自己指定的颜色起一个名字
这样,在需要的时候就可以根据name直接使用自定义的颜色

[html] view plaincopyprint?在CODE上查看代码片派生到我的代码片
  1. <span style="font-family:Comic Sans MS;"><?xml version="1.0" encoding="utf-8"?>  
  2. <resources>  
  3.     <color name="mycolor">#748751</color>  
  4. </resources></span>  


②在Java代码中使用:

如果是在res中已经定义好该自定义颜色,在java代码中只需直接调用即可:

[java] view plaincopyprint?在CODE上查看代码片派生到我的代码片
  1. <span style="font-family:Comic Sans MS;">int mycolor = getResources().getColor(R.color.mycolor);  
  2.         Button btn = (Button) findViewById(R.id.btn);  
  3.         btn.setBackgroundColor(mycolor);</span>  

如果是直接在java代码中定义,这里要注意哦,透明度不可以省去哦!!!就像这样  0xFF080287,前面的0x代表16进制:

[java] view plaincopyprint?在CODE上查看代码片派生到我的代码片
  1. <span style="font-family:Comic Sans MS;">int mycolor = 0xff123456;  
  2.         Button btn = (Button) findViewById(R.id.btn);  
  3.         btn.setBackgroundColor(mycolor);</span>  



③利用静态方法argb来设置颜色:

[java] view plaincopyprint?在CODE上查看代码片派生到我的代码片
  1. <span style="font-family:Comic Sans MS;">Button btn = (Button) findViewById(R.id.btn);  
  2.         btn.setBackgroundColor(Color.argb(0xff0x000x000x00));</span>  

argb()方法的参数依次为透明度,红,绿,蓝的大小,可以理解为浓度,这里组合起来的就是白色




0 0
原创粉丝点击