android badgeView(右上角数字提醒)

我们在使用如短信类的软件是时会有未看短信数字的提醒,本人在论坛看到这个效果,就给大家分享一下:





最重要的是BadgeView这个重写TextView的类:

  1. import android.content.Context;  
  2. import android.content.res.Resources;  
  3. import android.graphics.Color;  
  4. import android.graphics.Typeface;  
  5. import android.graphics.drawable.ShapeDrawable;  
  6. import android.graphics.drawable.shapes.RoundRectShape;  
  7. import android.util.AttributeSet;  
  8. import android.util.TypedValue;  
  9. import android.view.Gravity;  
  10. import android.view.View;  
  11. import android.view.ViewGroup;  
  12. import android.view.ViewGroup.LayoutParams;  
  13. import android.view.ViewParent;  
  14. import android.view.animation.AccelerateInterpolator;  
  15. import android.view.animation.AlphaAnimation;  
  16. import android.view.animation.Animation;  
  17. import android.view.animation.DecelerateInterpolator;  
  18. import android.widget.FrameLayout;  
  19. import android.widget.TabWidget;  
  20. import android.widget.TextView;  
  21.   
  22. /** 
  23.  * A simple text label view that can be applied as a "badge" to any given {@link android.view.View}.  
  24.  * This class is intended to be instantiated at runtime rather than included in XML layouts. 
  25.  *  
  26.  * @author Jeff Gilfelt 
  27.  */  
  28. public class BadgeView extends TextView {  
  29.   
  30.     public static final int POSITION_TOP_LEFT = 1;  
  31.     public static final int POSITION_TOP_RIGHT = 2;  
  32.     public static final int POSITION_BOTTOM_LEFT = 3;  
  33.     public static final int POSITION_BOTTOM_RIGHT = 4;  
  34.       
  35.     private static final int DEFAULT_MARGIN_DIP = 5;  
  36.     private static final int DEFAULT_LR_PADDING_DIP = 5;  
  37.     private static final int DEFAULT_CORNER_RADIUS_DIP = 8;  
  38.     private static final int DEFAULT_POSITION = POSITION_TOP_RIGHT;  
  39.     private static final int DEFAULT_BADGE_COLOR = Color.RED;  
  40.     private static final int DEFAULT_TEXT_COLOR = Color.WHITE;  
  41.       
  42.     private static Animation fadeIn;  
  43.     private static Animation fadeOut;  
  44.       
  45.     private Context context;  
  46.     private View target;  
  47.       
  48.     private int badgePosition;  
  49.     private int badgeMargin;  
  50.     private int badgeColor;  
  51.       
  52.     private boolean isShown;  
  53.       
  54.     private ShapeDrawable badgeBg;  
  55.       
  56.     private int targetTabIndex;  
  57.       
  58.     public BadgeView(Context context) {  
  59.         this(context, (AttributeSet) null, android.R.attr.textViewStyle);  
  60.     }  
  61.       
  62.     public BadgeView(Context context, AttributeSet attrs) {  
  63.          this(context, attrs, android.R.attr.textViewStyle);  
  64.     }  
  65.       
  66.     /** 
  67.      * Constructor - 
  68.      *  
  69.      * create a new BadgeView instance attached to a target {@link android.view.View}. 
  70.      * 
  71.      * @param context context for this view. 
  72.      * @param target the View to attach the badge to. 
  73.      */  
  74.     public BadgeView(Context context, View target) {  
  75.          this(context, null, android.R.attr.textViewStyle, target, 0);  
  76.     }  
  77.       
  78.     /** 
  79.      * Constructor - 
  80.      *  
  81.      * create a new BadgeView instance attached to a target {@link android.widget.TabWidget} 
  82.      * tab at a given index. 
  83.      * 
  84.      * @param context context for this view. 
  85.      * @param target the TabWidget to attach the badge to. 
  86.      * @param index the position of the tab within the target. 
  87.      */  
  88.     public BadgeView(Context context, TabWidget target, int index) {  
  89.         this(context, null, android.R.attr.textViewStyle, target, index);  
  90.     }  
  91.       
  92.     public BadgeView(Context context, AttributeSet attrs, int defStyle) {  
  93.         this(context, attrs, defStyle, null0);  
  94.     }  
  95.       
  96.     public BadgeView(Context context, AttributeSet attrs, int defStyle, View target, int tabIndex) {  
  97.         super(context, attrs, defStyle);  
  98.         init(context, target, tabIndex);  
  99.     }  
  100.   
  101.     private void init(Context context, View target, int tabIndex) {  
  102.           
  103.         this.context = context;  
  104.         this.target = target;  
  105.         this.targetTabIndex = tabIndex;  
  106.           
  107.         // apply defaults  
  108.         badgePosition = DEFAULT_POSITION;  
  109.         badgeMargin = dipToPixels(DEFAULT_MARGIN_DIP);  
  110.         badgeColor = DEFAULT_BADGE_COLOR;  
  111.           
  112.         setTypeface(Typeface.DEFAULT_BOLD);  
  113.         int paddingPixels = dipToPixels(DEFAULT_LR_PADDING_DIP);  
  114.         setPadding(paddingPixels, 0, paddingPixels, 0);  
  115.         setTextColor(DEFAULT_TEXT_COLOR);  
  116.           
  117.         fadeIn = new AlphaAnimation(01);  
  118.         fadeIn.setInterpolator(new DecelerateInterpolator());  
  119.         fadeIn.setDuration(200);  
  120.   
  121.         fadeOut = new AlphaAnimation(10);  
  122.         fadeOut.setInterpolator(new AccelerateInterpolator());  
  123.         fadeOut.setDuration(200);  
  124.           
  125.         isShown = false;  
  126.           
  127.         if (this.target != null) {  
  128.             applyTo(this.target);  
  129.         } else {  
  130.             show();  
  131.         }  
  132.           
  133.     }  
  134.   
  135.     private void applyTo(View target) {  
  136.           
  137.         LayoutParams lp = target.getLayoutParams();  
  138.         ViewParent parent = target.getParent();  
  139.         FrameLayout container = new FrameLayout(context);  
  140.           
  141.         if (target instanceof TabWidget) {  
  142.               
  143.             // set target to the relevant tab child container  
  144.             target = ((TabWidget) target).getChildTabViewAt(targetTabIndex);  
  145.             this.target = target;  
  146.               
  147.             ((ViewGroup) target).addView(container,   
  148.                     new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT));  
  149.               
  150.             this.setVisibility(View.GONE);  
  151.             container.addView(this);  
  152.               
  153.         } else {  
  154.               
  155.             // TODO verify that parent is indeed a ViewGroup  
  156.             ViewGroup group = (ViewGroup) parent;   
  157.             int index = group.indexOfChild(target);  
  158.               
  159.             group.removeView(target);  
  160.             group.addView(container, index, lp);  
  161.               
  162.             container.addView(target);  
  163.       
  164.             this.setVisibility(View.GONE);  
  165.             container.addView(this);  
  166.               
  167.             group.invalidate();  
  168.               
  169.         }  
  170.           
  171.     }  
  172.       
  173.     /** 
  174.      * Make the badge visible in the UI. 
  175.      *  
  176.      */  
  177.     public void show() {  
  178.         show(falsenull);  
  179.     }  
  180.       
  181.     /** 
  182.      * Make the badge visible in the UI. 
  183.      * 
  184.      * @param animate flag to apply the default fade-in animation. 
  185.      */  
  186.     public void show(boolean animate) {  
  187.         show(animate, fadeIn);  
  188.     }  
  189.       
  190.     /** 
  191.      * Make the badge visible in the UI. 
  192.      * 
  193.      * @param anim Animation to apply to the view when made visible. 
  194.      */  
  195.     public void show(Animation anim) {  
  196.         show(true, anim);  
  197.     }  
  198.       
  199.     /** 
  200.      * Make the badge non-visible in the UI. 
  201.      *  
  202.      */  
  203.     public void hide() {  
  204.         hide(falsenull);  
  205.     }  
  206.       
  207.     /** 
  208.      * Make the badge non-visible in the UI. 
  209.      * 
  210.      * @param animate flag to apply the default fade-out animation. 
  211.      */  
  212.     public void hide(boolean animate) {  
  213.         hide(animate, fadeOut);  
  214.     }  
  215.       
  216.     /** 
  217.      * Make the badge non-visible in the UI. 
  218.      * 
  219.      * @param anim Animation to apply to the view when made non-visible. 
  220.      */  
  221.     public void hide(Animation anim) {  
  222.         hide(true, anim);  
  223.     }  
  224.       
  225.     /** 
  226.      * Toggle the badge visibility in the UI. 
  227.      *  
  228.      */  
  229.     public void toggle() {  
  230.         toggle(falsenullnull);  
  231.     }  
  232.       
  233.     /** 
  234.      * Toggle the badge visibility in the UI. 
  235.      *  
  236.      * @param animate flag to apply the default fade-in/out animation. 
  237.      */  
  238.     public void toggle(boolean animate) {  
  239.         toggle(animate, fadeIn, fadeOut);  
  240.     }  
  241.       
  242.     /** 
  243.      * Toggle the badge visibility in the UI. 
  244.      * 
  245.      * @param animIn Animation to apply to the view when made visible. 
  246.      * @param animOut Animation to apply to the view when made non-visible. 
  247.      */  
  248.     public void toggle(Animation animIn, Animation animOut) {  
  249.         toggle(true, animIn, animOut);  
  250.     }  
  251.       
  252.     private void show(boolean animate, Animation anim) {  
  253.         if (getBackground() == null) {  
  254.             if (badgeBg == null) {  
  255.                 badgeBg = getDefaultBackground();  
  256.             }  
  257.             setBackgroundDrawable(badgeBg);  
  258.         }  
  259.         applyLayoutParams();  
  260.           
  261.         if (animate) {  
  262.             this.startAnimation(anim);  
  263.         }  
  264.         this.setVisibility(View.VISIBLE);  
  265.         isShown = true;  
  266.     }  
  267.       
  268.     private void hide(boolean animate, Animation anim) {  
  269.         this.setVisibility(View.GONE);  
  270.         if (animate) {  
  271.             this.startAnimation(anim);  
  272.         }  
  273.         isShown = false;  
  274.     }  
  275.       
  276.     private void toggle(boolean animate, Animation animIn, Animation animOut) {  
  277.         if (isShown) {  
  278.             hide(animate && (animOut != null), animOut);      
  279.         } else {  
  280.             show(animate && (animIn != null), animIn);  
  281.         }  
  282.     }  
  283.       
  284.     /** 
  285.      * Increment the numeric badge label. If the current badge label cannot be converted to 
  286.      * an integer value, its label will be set to "0". 
  287.      *  
  288.      * @param offset the increment offset. 
  289.      */  
  290.     public int increment(int offset) {  
  291.         CharSequence txt = getText();  
  292.         int i;  
  293.         if (txt != null) {  
  294.             try {  
  295.                 i = Integer.parseInt(txt.toString());  
  296.             } catch (NumberFormatException e) {  
  297.                 i = 0;  
  298.             }  
  299.         } else {  
  300.             i = 0;  
  301.         }  
  302.         i = i + offset;  
  303.         setText(String.valueOf(i));  
  304.         return i;  
  305.     }  
  306.       
  307.     /** 
  308.      * Decrement the numeric badge label. If the current badge label cannot be converted to 
  309.      * an integer value, its label will be set to "0". 
  310.      *  
  311.      * @param offset the decrement offset. 
  312.      */  
  313.     public int decrement(int offset) {  
  314.         return increment(-offset);  
  315.     }  
  316.       
  317.     private ShapeDrawable getDefaultBackground() {  
  318.           
  319.         int r = dipToPixels(DEFAULT_CORNER_RADIUS_DIP);  
  320.         float[] outerR = new float[] {r, r, r, r, r, r, r, r};  
  321.           
  322.         RoundRectShape rr = new RoundRectShape(outerR, nullnull);  
  323.         ShapeDrawable drawable = new ShapeDrawable(rr);  
  324.         drawable.getPaint().setColor(badgeColor);  
  325.           
  326.         return drawable;  
  327.           
  328.     }  
  329.       
  330.     private void applyLayoutParams() {  
  331.           
  332.         FrameLayout.LayoutParams lp = new FrameLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);  
  333.           
  334.         switch (badgePosition) {  
  335.         case POSITION_TOP_LEFT:  
  336.             lp.gravity = Gravity.LEFT | Gravity.TOP;  
  337.             lp.setMargins(badgeMargin, badgeMargin, 00);  
  338.             break;  
  339.         case POSITION_TOP_RIGHT:  
  340.             lp.gravity = Gravity.RIGHT | Gravity.TOP;  
  341.             lp.setMargins(0, badgeMargin, badgeMargin, 0);  
  342.             break;  
  343.         case POSITION_BOTTOM_LEFT:  
  344.             lp.gravity = Gravity.LEFT | Gravity.BOTTOM;  
  345.             lp.setMargins(badgeMargin, 00, badgeMargin);  
  346.             break;  
  347.         case POSITION_BOTTOM_RIGHT:  
  348.             lp.gravity = Gravity.RIGHT | Gravity.BOTTOM;  
  349.             lp.setMargins(00, badgeMargin, badgeMargin);  
  350.             break;  
  351.         default:  
  352.             break;  
  353.         }  
  354.           
  355.         setLayoutParams(lp);  
  356.           
  357.     }  
  358.   
  359.     /** 
  360.      * Returns the target View this badge has been attached to. 
  361.      *  
  362.      */  
  363.     public View getTarget() {  
  364.         return target;  
  365.     }  
  366.   
  367.     /** 
  368.      * Is this badge currently visible in the UI? 
  369.      *  
  370.      */  
  371.     @Override  
  372.     public boolean isShown() {  
  373.         return isShown;  
  374.     }  
  375.   
  376.     /** 
  377.      * Returns the positioning of this badge. 
  378.      *  
  379.      * one of POSITION_TOP_LEFT, POSITION_TOP_RIGHT, POSITION_BOTTOM_LEFT, POSITION_BOTTOM_RIGHT. 
  380.      *  
  381.      */  
  382.     public int getBadgePosition() {  
  383.         return badgePosition;  
  384.     }  
  385.   
  386.     /** 
  387.      * Set the positioning of this badge. 
  388.      *  
  389.      * @param layoutPosition one of POSITION_TOP_LEFT, POSITION_TOP_RIGHT, POSITION_BOTTOM_LEFT, POSITION_BOTTOM_RIGHT. 
  390.      *  
  391.      */  
  392.     public void setBadgePosition(int layoutPosition) {  
  393.         this.badgePosition = layoutPosition;  
  394.     }  
  395.   
  396.     /** 
  397.      * Returns the horizontal/vertical margin from the target View that is applied to this badge. 
  398.      *  
  399.      */  
  400.     public int getBadgeMargin() {  
  401.         return badgeMargin;  
  402.     }  
  403.   
  404.     /** 
  405.      * Set the horizontal/vertical margin from the target View that is applied to this badge. 
  406.      *  
  407.      * @param badgeMargin the margin in pixels. 
  408.      */  
  409.     public void setBadgeMargin(int badgeMargin) {  
  410.         this.badgeMargin = badgeMargin;  
  411.     }  
  412.       
  413.     /** 
  414.      * Returns the color value of the badge background. 
  415.      *  
  416.      */  
  417.     public int getBadgeBackgroundColor() {  
  418.         return badgeColor;  
  419.     }  
  420.   
  421.     /** 
  422.      * Set the color value of the badge background. 
  423.      *  
  424.      * @param badgeColor the badge background color. 
  425.      */  
  426.     public void setBadgeBackgroundColor(int badgeColor) {  
  427.         this.badgeColor = badgeColor;  
  428.         badgeBg = getDefaultBackground();  
  429.     }  
  430.       
  431.     private int dipToPixels(int dip) {  
  432.         Resources r = getResources();  
  433.         float px = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dip, r.getDisplayMetrics());  
  434.         return (int) px;  
  435.     }  
  436.   
  437. }  
import android.content.Context;
import android.content.res.Resources;
import android.graphics.Color;
import android.graphics.Typeface;
import android.graphics.drawable.ShapeDrawable;
import android.graphics.drawable.shapes.RoundRectShape;
import android.util.AttributeSet;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.view.ViewParent;
import android.view.animation.AccelerateInterpolator;
import android.view.animation.AlphaAnimation;
import android.view.animation.Animation;
import android.view.animation.DecelerateInterpolator;
import android.widget.FrameLayout;
import android.widget.TabWidget;
import android.widget.TextView;

/**
 * A simple text label view that can be applied as a "badge" to any given {@link android.view.View}. 
 * This class is intended to be instantiated at runtime rather than included in XML layouts.
 * 
 * @author Jeff Gilfelt
 */
public class BadgeView extends TextView {

	public static final int POSITION_TOP_LEFT = 1;
	public static final int POSITION_TOP_RIGHT = 2;
	public static final int POSITION_BOTTOM_LEFT = 3;
	public static final int POSITION_BOTTOM_RIGHT = 4;
	
	private static final int DEFAULT_MARGIN_DIP = 5;
	private static final int DEFAULT_LR_PADDING_DIP = 5;
	private static final int DEFAULT_CORNER_RADIUS_DIP = 8;
	private static final int DEFAULT_POSITION = POSITION_TOP_RIGHT;
	private static final int DEFAULT_BADGE_COLOR = Color.RED;
	private static final int DEFAULT_TEXT_COLOR = Color.WHITE;
	
	private static Animation fadeIn;
	private static Animation fadeOut;
	
	private Context context;
	private View target;
	
	private int badgePosition;
	private int badgeMargin;
	private int badgeColor;
	
	private boolean isShown;
	
	private ShapeDrawable badgeBg;
	
	private int targetTabIndex;
	
	public BadgeView(Context context) {
		this(context, (AttributeSet) null, android.R.attr.textViewStyle);
	}
	
	public BadgeView(Context context, AttributeSet attrs) {
		 this(context, attrs, android.R.attr.textViewStyle);
	}
	
	/**
     * Constructor -
     * 
     * create a new BadgeView instance attached to a target {@link android.view.View}.
     *
     * @param context context for this view.
     * @param target the View to attach the badge to.
     */
	public BadgeView(Context context, View target) {
		 this(context, null, android.R.attr.textViewStyle, target, 0);
	}
	
	/**
     * Constructor -
     * 
     * create a new BadgeView instance attached to a target {@link android.widget.TabWidget}
     * tab at a given index.
     *
     * @param context context for this view.
     * @param target the TabWidget to attach the badge to.
     * @param index the position of the tab within the target.
     */
	public BadgeView(Context context, TabWidget target, int index) {
		this(context, null, android.R.attr.textViewStyle, target, index);
	}
	
	public BadgeView(Context context, AttributeSet attrs, int defStyle) {
		this(context, attrs, defStyle, null, 0);
	}
	
	public BadgeView(Context context, AttributeSet attrs, int defStyle, View target, int tabIndex) {
		super(context, attrs, defStyle);
		init(context, target, tabIndex);
	}

	private void init(Context context, View target, int tabIndex) {
		
		this.context = context;
		this.target = target;
		this.targetTabIndex = tabIndex;
		
		// apply defaults
		badgePosition = DEFAULT_POSITION;
		badgeMargin = dipToPixels(DEFAULT_MARGIN_DIP);
		badgeColor = DEFAULT_BADGE_COLOR;
		
		setTypeface(Typeface.DEFAULT_BOLD);
		int paddingPixels = dipToPixels(DEFAULT_LR_PADDING_DIP);
		setPadding(paddingPixels, 0, paddingPixels, 0);
		setTextColor(DEFAULT_TEXT_COLOR);
		
		fadeIn = new AlphaAnimation(0, 1);
		fadeIn.setInterpolator(new DecelerateInterpolator());
		fadeIn.setDuration(200);

		fadeOut = new AlphaAnimation(1, 0);
		fadeOut.setInterpolator(new AccelerateInterpolator());
		fadeOut.setDuration(200);
		
		isShown = false;
		
		if (this.target != null) {
			applyTo(this.target);
		} else {
			show();
		}
		
	}

	private void applyTo(View target) {
		
		LayoutParams lp = target.getLayoutParams();
		ViewParent parent = target.getParent();
		FrameLayout container = new FrameLayout(context);
		
		if (target instanceof TabWidget) {
			
			// set target to the relevant tab child container
			target = ((TabWidget) target).getChildTabViewAt(targetTabIndex);
			this.target = target;
			
			((ViewGroup) target).addView(container, 
					new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT));
			
			this.setVisibility(View.GONE);
			container.addView(this);
			
		} else {
			
			// TODO verify that parent is indeed a ViewGroup
			ViewGroup group = (ViewGroup) parent; 
			int index = group.indexOfChild(target);
			
			group.removeView(target);
			group.addView(container, index, lp);
			
			container.addView(target);
	
			this.setVisibility(View.GONE);
			container.addView(this);
			
			group.invalidate();
			
		}
		
	}
	
	/**
     * Make the badge visible in the UI.
     * 
     */
	public void show() {
		show(false, null);
	}
	
	/**
     * Make the badge visible in the UI.
     *
     * @param animate flag to apply the default fade-in animation.
     */
	public void show(boolean animate) {
		show(animate, fadeIn);
	}
	
	/**
     * Make the badge visible in the UI.
     *
     * @param anim Animation to apply to the view when made visible.
     */
	public void show(Animation anim) {
		show(true, anim);
	}
	
	/**
     * Make the badge non-visible in the UI.
     * 
     */
	public void hide() {
		hide(false, null);
	}
	
	/**
     * Make the badge non-visible in the UI.
     *
     * @param animate flag to apply the default fade-out animation.
     */
	public void hide(boolean animate) {
		hide(animate, fadeOut);
	}
	
	/**
     * Make the badge non-visible in the UI.
     *
     * @param anim Animation to apply to the view when made non-visible.
     */
	public void hide(Animation anim) {
		hide(true, anim);
	}
	
	/**
     * Toggle the badge visibility in the UI.
     * 
     */
	public void toggle() {
		toggle(false, null, null);
	}
	
	/**
     * Toggle the badge visibility in the UI.
     * 
     * @param animate flag to apply the default fade-in/out animation.
     */
	public void toggle(boolean animate) {
		toggle(animate, fadeIn, fadeOut);
	}
	
	/**
     * Toggle the badge visibility in the UI.
     *
     * @param animIn Animation to apply to the view when made visible.
     * @param animOut Animation to apply to the view when made non-visible.
     */
	public void toggle(Animation animIn, Animation animOut) {
		toggle(true, animIn, animOut);
	}
	
	private void show(boolean animate, Animation anim) {
		if (getBackground() == null) {
			if (badgeBg == null) {
				badgeBg = getDefaultBackground();
			}
			setBackgroundDrawable(badgeBg);
		}
		applyLayoutParams();
		
		if (animate) {
			this.startAnimation(anim);
		}
		this.setVisibility(View.VISIBLE);
		isShown = true;
	}
	
	private void hide(boolean animate, Animation anim) {
		this.setVisibility(View.GONE);
		if (animate) {
			this.startAnimation(anim);
		}
		isShown = false;
	}
	
	private void toggle(boolean animate, Animation animIn, Animation animOut) {
		if (isShown) {
			hide(animate && (animOut != null), animOut);	
		} else {
			show(animate && (animIn != null), animIn);
		}
	}
	
	/**
     * Increment the numeric badge label. If the current badge label cannot be converted to
     * an integer value, its label will be set to "0".
     * 
     * @param offset the increment offset.
     */
	public int increment(int offset) {
		CharSequence txt = getText();
		int i;
		if (txt != null) {
			try {
				i = Integer.parseInt(txt.toString());
			} catch (NumberFormatException e) {
				i = 0;
			}
		} else {
			i = 0;
		}
		i = i + offset;
		setText(String.valueOf(i));
		return i;
	}
	
	/**
     * Decrement the numeric badge label. If the current badge label cannot be converted to
     * an integer value, its label will be set to "0".
     * 
     * @param offset the decrement offset.
     */
	public int decrement(int offset) {
		return increment(-offset);
	}
	
	private ShapeDrawable getDefaultBackground() {
		
		int r = dipToPixels(DEFAULT_CORNER_RADIUS_DIP);
		float[] outerR = new float[] {r, r, r, r, r, r, r, r};
        
		RoundRectShape rr = new RoundRectShape(outerR, null, null);
		ShapeDrawable drawable = new ShapeDrawable(rr);
		drawable.getPaint().setColor(badgeColor);
		
		return drawable;
		
	}
	
	private void applyLayoutParams() {
		
		FrameLayout.LayoutParams lp = new FrameLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
		
		switch (badgePosition) {
		case POSITION_TOP_LEFT:
			lp.gravity = Gravity.LEFT | Gravity.TOP;
			lp.setMargins(badgeMargin, badgeMargin, 0, 0);
			break;
		case POSITION_TOP_RIGHT:
			lp.gravity = Gravity.RIGHT | Gravity.TOP;
			lp.setMargins(0, badgeMargin, badgeMargin, 0);
			break;
		case POSITION_BOTTOM_LEFT:
			lp.gravity = Gravity.LEFT | Gravity.BOTTOM;
			lp.setMargins(badgeMargin, 0, 0, badgeMargin);
			break;
		case POSITION_BOTTOM_RIGHT:
			lp.gravity = Gravity.RIGHT | Gravity.BOTTOM;
			lp.setMargins(0, 0, badgeMargin, badgeMargin);
			break;
		default:
			break;
		}
		
		setLayoutParams(lp);
		
	}

	/**
     * Returns the target View this badge has been attached to.
     * 
     */
	public View getTarget() {
		return target;
	}

	/**
     * Is this badge currently visible in the UI?
     * 
     */
	@Override
	public boolean isShown() {
		return isShown;
	}

	/**
     * Returns the positioning of this badge.
     * 
     * one of POSITION_TOP_LEFT, POSITION_TOP_RIGHT, POSITION_BOTTOM_LEFT, POSITION_BOTTOM_RIGHT.
     * 
     */
	public int getBadgePosition() {
		return badgePosition;
	}

	/**
     * Set the positioning of this badge.
     * 
     * @param layoutPosition one of POSITION_TOP_LEFT, POSITION_TOP_RIGHT, POSITION_BOTTOM_LEFT, POSITION_BOTTOM_RIGHT.
     * 
     */
	public void setBadgePosition(int layoutPosition) {
		this.badgePosition = layoutPosition;
	}

	/**
     * Returns the horizontal/vertical margin from the target View that is applied to this badge.
     * 
     */
	public int getBadgeMargin() {
		return badgeMargin;
	}

	/**
     * Set the horizontal/vertical margin from the target View that is applied to this badge.
     * 
     * @param badgeMargin the margin in pixels.
     */
	public void setBadgeMargin(int badgeMargin) {
		this.badgeMargin = badgeMargin;
	}
	
	/**
     * Returns the color value of the badge background.
     * 
     */
	public int getBadgeBackgroundColor() {
		return badgeColor;
	}

	/**
     * Set the color value of the badge background.
     * 
     * @param badgeColor the badge background color.
     */
	public void setBadgeBackgroundColor(int badgeColor) {
		this.badgeColor = badgeColor;
		badgeBg = getDefaultBackground();
	}
	
	private int dipToPixels(int dip) {
		Resources r = getResources();
		float px = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dip, r.getDisplayMetrics());
		return (int) px;
	}

}


现在我们来使用它;

  1. import android.app.Activity;  
  2. import android.graphics.Color;  
  3. import android.os.Bundle;  
  4. import android.view.View;  
  5. import android.view.View.OnClickListener;  
  6. import android.view.animation.BounceInterpolator;  
  7. import android.view.animation.TranslateAnimation;  
  8. import android.widget.Button;  
  9.   
  10. public class BadgerActivity extends Activity {  
  11.     /** Called when the activity is first created. */  
  12.     Button  btn ;  
  13.     Button  btn1 ;  
  14.     BadgeView badge;  
  15.     BadgeView badge1;  
  16.     @Override  
  17.     public void onCreate(Bundle savedInstanceState) {  
  18.         super.onCreate(savedInstanceState);  
  19.         setContentView(R.layout.main);  
  20.         btn =(Button) findViewById(R.id.btn);  
  21.         btn1 =(Button) findViewById(R.id.btn1);  
  22.           
  23.         badge = new BadgeView(this,btn);  
  24.         badge.setText("0");  
  25.         btn.setOnClickListener(new OnClickListener() {  
  26.               
  27.             @Override  
  28.             public void onClick(View v) {  
  29.                 // TODO Auto-generated method stub  
  30.               if(badge.isShown()){  
  31.                   badge.increment(1);  
  32.               }else{  
  33.                   badge.show();  
  34.               }  
  35.             }  
  36.         });  
  37.         badge1 = new BadgeView(this, btn1);  
  38.         badge1.setText("123");  
  39.         badge1.setBadgePosition(BadgeView.POSITION_TOP_LEFT);  
  40.         badge1.setBadgeMargin(15);  
  41.         badge1.setBadgeBackgroundColor(Color.parseColor("#A4C639"));  
  42.         btn1.setOnClickListener(new OnClickListener() {  
  43.             @Override  
  44.             public void onClick(View v) {  
  45.                 TranslateAnimation anim = new TranslateAnimation(-100000);  
  46.                 anim.setInterpolator(new BounceInterpolator());  
  47.                 anim.setDuration(1000);  
  48.                 badge1.toggle(anim, null);  
  49.             }  
  50.         });     
  51.           
  52.     }  
  53. }  
import android.app.Activity;
import android.graphics.Color;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.animation.BounceInterpolator;
import android.view.animation.TranslateAnimation;
import android.widget.Button;

public class BadgerActivity extends Activity {
    /** Called when the activity is first created. */
	Button  btn ;
	Button  btn1 ;
	BadgeView badge;
	BadgeView badge1;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        btn =(Button) findViewById(R.id.btn);
        btn1 =(Button) findViewById(R.id.btn1);
        
        badge = new BadgeView(this,btn);
        badge.setText("0");
        btn.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
			  if(badge.isShown()){
				  badge.increment(1);
			  }else{
				  badge.show();
			  }
			}
		});
        badge1 = new BadgeView(this, btn1);
    	badge1.setText("123");
    	badge1.setBadgePosition(BadgeView.POSITION_TOP_LEFT);
    	badge1.setBadgeMargin(15);
    	badge1.setBadgeBackgroundColor(Color.parseColor("#A4C639"));
    	btn1.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				TranslateAnimation anim = new TranslateAnimation(-100, 0, 0, 0);
		        anim.setInterpolator(new BounceInterpolator());
		        anim.setDuration(1000);
		    	badge1.toggle(anim, null);
			}
		});   
        
    }
}


BadgeView原始项目上传csdn,http://download.csdn.net/detail/shaojie519/3861841

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
如果您是想在 Android 应用程序的上角添加一个标签,您可以使用 Toolbar 控件并在其中添加一个 Menu。在菜单中,您可以添加一个 MenuItem 并设置它的图标和文本。这个 MenuItem 就可以作为上角的标签来使用。 以下是一个示例代码片段,可以帮助您实现这个功能: ```xml <android.support.v7.widget.Toolbar android:id="@+id/toolbar" android:layout_width="match_parent" android:layout_height="?attr/actionBarSize" android:background="?attr/colorPrimary" app:popupTheme="@style/AppTheme.PopupOverlay"> <Menu xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" tools:context=".MainActivity"> <item android:id="@+id/action_label" android:title="Label" android:icon="@drawable/ic_label" app:showAsAction="always" /> </Menu> </android.support.v7.widget.Toolbar> ``` 在这个示例中,我们使用了一个 Toolbar 控件,并在其中添加了一个 Menu。在 Menu 中,我们添加了一个 MenuItem,并设置了它的图标和文本,同时将它的 showAsAction 属性设置为 always,这样这个 MenuItem 就会一直显示在 Toolbar 的侧。 在您的 Activity 或 Fragment 中,您可以通过以下代码来处理这个 MenuItem 的点击事件: ```java @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case R.id.action_label: // 处理标签点击事件 return true; default: return super.onOptionsItemSelected(item); } } ``` 这样,当用户点击标签时,onOptionsItemSelected() 方法会被调用,并且您可以在其中处理相应的逻辑。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值