android 给 button 添加边框及底色

一、如下是设置按钮的右边框和底边框颜色为红色,边框大小为3dp,以下图:html

在drawable新建一个 buttonstyle.xml的文件,内容以下:java

[html]  view plain copy
  1. <?xml version="1.0" encoding="UTF-8"?>  
  2. <layer-list xmlns:android="http://schemas.android.com/apk/res/android">   
  3. <!-- 连框颜色值 --><item>   
  4.       <shape>   
  5.             <solid android:color="#ff0000" />   
  6.       </shape>   
  7. </item>   
  8. <!-- 主体背景颜色值 -->  
  9. <item android:bottom="3dp" android:right="3dp">   
  10.      <shape>   
  11.            <solid android:color="#ffffff" />  
  12.              
  13.            <padding android:bottom="10dp"  
  14.                 android:left="10dp"  
  15.                 android:right="10dp"  
  16.                 android:top="10dp" />  
  17.      </shape>       
  18. </item>  
  19. </layer-list>  

 

而后在布局文件里面的Button里面设置以下:android

  1. <Button  
  2.    android:id="@+id/button1"  
  3.    android:layout_width="wrap_content"  
  4.    android:layout_height="wrap_content"  
  5.    android:text="Button1"  
  6.    android:background="@drawable/buttonstyle" />  


二、此文版权属于做者全部,任何人、媒体或者网站转载、借用都必须征得做者本人赞成!ide

[java]  view plain copy 在CODE上查看代码片 派生到个人代码片
  1. GradientDrawable drawable = new GradientDrawable();  
  2. drawable.setShape(GradientDrawable.RECTANGLE); // 画框  
  3. drawable.setStroke(1, Color.BLUE); // 边框粗细及颜色  
  4. drawable.setColor(0x22FFFF00); // 边框内部颜色  
  5.   
  6. mFullscreenBtn = new Button(ctx);  

  1. mFullscreenBtn.setBackgroundDrawable(drawable); // 设置背景(效果就是有边框及底色)