自定義顯示小紅點的android Button按鈕

效果:

 

 

實現原理:

繼承自Button的一個控件,小紅點和數字,是直接繪製到Canvas上的,老是在右上角。之看以看起來,角標已經超出了Button,是由於在繪製Button的時候,對Canvas進行了縮放。譬如:html

 

 

[html] view plain copyjava

  1. <com.carlos.notificatoinbutton.library.NotificationButton  
  2.     android:id="@+id/button4"  
  3.     android:layout_width="100dp"  
  4.     android:layout_height="100dp"  
  5.     android:layout_marginTop="15dp"  
  6.     android:background="@mipmap/wechat"  
  7.     notButton:circleBgColor="@android:color/holo_red_light"  
  8.     notButton:circleSize="12dp"  
  9.     notButton:textColor="@android:color/holo_green_dark" />  

這樣的一個NotificationButton,設置的寬和高爲100dp方形,circleSize,就是小紅點的大小,爲12dp。這樣設置的話,實際上,你看到的Button的大小,只有88dp,是總的寬度減去小紅點的大小。android

 

使用方法:

在android studio中引用:git

 

[plain] view plain copygithub

  1. compile 'com.carlos.notificatoinbutton:buttonlibrary:1.0.5'  


 

 

而後在佈局文件中:app

 

[html] view plain copyide

  1. <com.carlos.notificatoinbutton.library.NotificationButton  
  2.     android:id="@+id/button5"  
  3.     android:layout_width="100dp"  
  4.     android:layout_height="100dp"  
  5.     android:layout_marginTop="15dp"  
  6.     android:background="@mipmap/wechat"  
  7.     notButton:circleBgColor="@android:color/holo_red_light"  
  8.     notButton:circleSize="12dp"  
  9.     notButton:textColor="@android:color/holo_green_dark" />  


由於它是繼承自Button,全部Button的屬性,均可以使用。除些以外,還有三個自定義屬性:佈局

 

[html] view plain copyspa

  1. <!--小紅點的顏色-->  
  2.         notButton:circleBgColor="@android:color/holo_red_light"  
  3.         <!--小紅點大小-->  
  4.         notButton:circleSize="12dp"  
  5.         <!--小紅點上字的顏色-->  
  6.         notButton:textColor="@android:color/holo_green_dark"  


 

而後是在java代碼中:.net

 

[java] view plain copy

  1. @Override  
  2.    protected void onCreate(Bundle savedInstanceState) {  
  3.        super.onCreate(savedInstanceState);  
  4.        setContentView(R.layout.activity_main);  
  5.        button2 = (NotificationButton) findViewById(R.id.button2);  
  6.        button3 = (NotificationButton) findViewById(R.id.button3);  
  7.        button4 = (NotificationButton) findViewById(R.id.button4);  
  8.        button5 = (NotificationButton) findViewById(R.id.button5);  
  9.        button2.setNotificationNumber(120);  
  10.        button3.setNotificationNumber(85);  
  11.        button4.setNotificationNumber(9);  
  12.        button5.setNotificationNumber(0);  
  13.    }  


只有一個方法,setNotificationNumber方法,設置了它,就能夠直接顯示通知數量了,

大於99的,顯示99+,

小於等於0的,不顯示。

 

源代碼地址:

 

https://github.com/ws123/NotificationButton

相關文章
相關標籤/搜索