Android之背景颜色小知识(笔记)

来源:互联网 发布:银河麒麟软件下载 编辑:程序博客网 时间:2024/05/16 15:30

一、ListView的item背景(自定义颜色)

通常情况下,ListView的item背景用的是图片资源,下面跟大家分享一下使用颜色资源,即自定义一种颜色,当item聚焦、按压、选择的时候,可以显示我们自定义的颜色,好了废话不多说,直接分享代码:

1.首先在drawable目录下面新建一个list_item_color.xml,自定义我们需要的颜色

[html] view plain copy
  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <shape xmlns:android="http://schemas.android.com/apk/res/android"  
  3.     android:shape="rectangle" >  
  4.   
  5.     <solid android:color="#87CEFF" /> <!-- 自定义为蓝色 -->  
  6.   
  7. </shape>  


2.继续在drawable目录下新建一个list_item_bg.xml,在这里使用我们自定义的颜色,

[html] view plain copy
  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <selector xmlns:android="http://schemas.android.com/apk/res/android">  
  3.       
  4.     <item android:drawable="@drawable/list_item_selcet_color" android:state_pressed="true"/> <!-- 按压时变成我们自定义的颜色 -->  
  5.     <item android:drawable="@drawable/list_item_selcet_color" android:state_selected="true"/> <!-- 选择时变成我们自定义的颜色 -->  
  6.   
  7. </selector>  


3.在layout目录下item布局文件中使用我们的背景,我这里是home_listview_item.xml:

[html] view plain copy
  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"  
  3.     android:layout_width="match_parent"  
  4.     android:layout_height="match_parent"  
  5.     android:background="@drawable/list_item_select_bg"  将我们自定义的设置为背景即可,  
  6.     android:orientation="vertical"  
  7.     android:padding="5dp" >  
  8. <!-- 此处省略n行-->  
  9. </LinearLayout>  


好了,大功告成,回去上传效果图,我知道童鞋们都喜欢看图,有图有真相嘛。大笑

 

二、按压item时改变字体颜色

我们应该都见过类似的效果,就是当我们按下ListView的item时,在发现item背景颜色改变的同时,字体也会变色,其实实现起来也是很简单的。

1.在color目录下新建一个list_view_item_black_color.xml文件,

[html] view plain copy
  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <selector xmlns:android="http://schemas.android.com/apk/res/android">  
  3.     <item android:state_focused="true" android:color="#000000"/> <!-- 聚焦时为黑色 -->  
  4.     <item android:state_pressed="true" android:color="#ffffff"/> <!-- 按下时为白色 -->  
  5.     <item android:state_selected="true" android:color="#000000"/> <!-- 选择时为黑色 -->  
  6.     <item android:color="#000000"/> <!-- 普通状态下为黑色 -->  
  7. </selector>  

 

2.在layout资源目录下使用:

[html] view plain copy
  1. <!-- 此处上下省略n行 -->  
  2.   <TextView  
  3.                     android:id="@+id/home_item_content"  
  4.                     android:layout_width="fill_parent"  
  5.                     android:layout_height="wrap_content"  
  6.                     android:padding="2dp"  
  7.                     android:text="今天心情很好"  
  8.                     android:textColor="@color/list_view_item_black_color"  
  9.                     android:textSize="18sp" />  


好了,很简单,当做自己留下的笔记,备忘。

0 0
原创粉丝点击