xamarin.android 给View控件 添加数字提醒效果-BadgeView

本文代码从java项目移植到.net项目   java开源项目:https://github.com/jgilfelt/android-viewbadger

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using Android.App;
using Android.Content;
using Android.OS;
using Android.Runtime;
using Android.Views;
using Android.Widget;
using Android.Graphics;

using Java.Lang;
using Android.Util;
using Android.Content.Res;
using Android.Views.Animations;
using Android.Graphics.Drawables;
using Android.Graphics.Drawables.Shapes;
using static Android.Resource;
using static Android.App.ActionBar;

namespace Dorid.UI
{
    public class BadgeView : TextView
    {
        public const int POSITION_TOP_LEFT = 1;
        public const int POSITION_TOP_RIGHT = 2;
        public const int POSITION_BOTTOM_LEFT = 3;
        public const int POSITION_BOTTOM_RIGHT = 4;
        public const int POSITION_CENTER = 5;

        private const int DEFAULT_MARGIN_DIP = 5;
        private const int DEFAULT_LR_PADDING_DIP = 5;
        private const int DEFAULT_CORNER_RADIUS_DIP = 8;
        private const int DEFAULT_POSITION = POSITION_TOP_RIGHT;
        private static Android.Graphics.Color DEFAULT_BADGE_COLOR = Android.Graphics.Color.ParseColor("#CCFF0000"); //Color.RED;
        private static Android.Graphics.Color DEFAULT_TEXT_COLOR = Android.Graphics.Color.White;

        private static Android.Views.Animations.Animation fadeIn;
        private static Android.Views.Animations.Animation fadeOut;

        private Context context;
        private View target;

        private int badgePosition;
        private int badgeMarginH;
        private int badgeMarginV;
        private Android.Graphics.Color badgeColor;

        private bool isShown;

        private ShapeDrawable badgeBg;

        private int targetTabIndex;

        public BadgeView(Context context):this(context,(IAttributeSet)null, Android.Resource.Attribute.TextViewStyle)
        {

        }

        public BadgeView(Context context, IAttributeSet attrs) : this(context, attrs, Android.Resource.Attribute.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.Resource.Attribute.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.Resource.Attribute.TextViewStyle,target,index)
        {

        }

        public BadgeView(Context context, IAttributeSet attrs, int defStyle):this(context,attrs,defStyle,null,0)
        {

        }

        public BadgeView(Context context, IAttributeSet attrs, int defStyle, View target, int tabIndex):base(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;
            badgeMarginH = DipToPixels(DEFAULT_MARGIN_DIP);
            badgeMarginV = badgeMarginH;
            badgeColor = DEFAULT_BADGE_COLOR;

            Typeface = Typeface.DefaultBold;
            int paddingPixels = DipToPixels(DEFAULT_LR_PADDING_DIP);

            SetPadding(paddingPixels, 0, paddingPixels, 0);
            SetTextColor(DEFAULT_TEXT_COLOR);

            fadeIn = new AlphaAnimation(0, 1);
            fadeIn.Interpolator = new DecelerateInterpolator();
            fadeIn.Duration = 200;

            fadeOut = new AlphaAnimation(1, 0);
            fadeOut.Interpolator = new DecelerateInterpolator();
            fadeOut.Duration = 200;

            isShown = false;

            if (this.target != null)
            {
                ApplyTo(this.target);
            }
            else
            {
                Show();
            }

        }

        private void ApplyTo(View target)
        {

            ViewGroup.LayoutParams lp = target.LayoutParameters;
            IViewParent parent = target.Parent;
            FrameLayout container = new FrameLayout(context);

            if (target is TabWidget) {

                // set target to the relevant tab child container
                target = ((TabWidget)target).GetChildTabViewAt(targetTabIndex);
                this.target = target;

                ((ViewGroup)target).AddView(container,
                        new LayoutParams(LayoutParams.FillParent, LayoutParams.FillParent));

                this.Visibility= ViewStates.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.Visibility= ViewStates.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(bool 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(Android.Views.Animations.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(bool 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(Android.Views.Animations.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(bool 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(Android.Views.Animations.Animation animIn, Android.Views.Animations.Animation animOut)
        {
            Toggle(true, animIn, animOut);
        }

        private void Show(bool animate, Android.Views.Animations.Animation anim)
        {

            if (Background == null)
            {
                if (badgeBg == null)
                {
                    badgeBg = getDefaultBackground();
                }

                SetBackgroundDrawable(badgeBg);
            }
            ApplyLayoutParams();

            if (animate)
            {
                this.StartAnimation(anim);
            }
            this.Visibility = ViewStates.Visible;
            isShown = true;
        }

        private void Hide(bool animate, Android.Views.Animations.Animation anim)
        {
            this.Visibility = ViewStates.Gone;
            if (animate)
            {
                this.StartAnimation(anim);
            }
            isShown = false;
        }

        private void Toggle(bool animate, Android.Views.Animations.Animation animIn, Android.Views.Animations.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)
        {
            var txt = Text;
            int i;
            if (txt != null)
            {
                try
                {
                    i = Convert.ToInt32(txt.ToString());
                }
                catch (NumberFormatException e)
                {
                    i = 0;
                }
            }
            else
            {
                i = 0;
            }
            i = i + offset;
            //Text = 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.Paint.Color = badgeColor;

            return drawable;

        }

        private void ApplyLayoutParams()
        {

            FrameLayout.LayoutParams lp = new FrameLayout.LayoutParams(LayoutParams.WrapContent, LayoutParams.WrapContent);

            switch (badgePosition)
            {
                case POSITION_TOP_LEFT:
                    lp.Gravity = GravityFlags.Left | GravityFlags.Top;
                    lp.SetMargins(badgeMarginH, badgeMarginV, 0, 0);
                    break;
                case POSITION_TOP_RIGHT:
                    lp.Gravity = GravityFlags.Right | GravityFlags.Top;
                    lp.SetMargins(0, badgeMarginV, badgeMarginH, 0);
                    break;
                case POSITION_BOTTOM_LEFT:
                    lp.Gravity = GravityFlags.Left | GravityFlags.Bottom;
                    lp.SetMargins(badgeMarginH, 0, 0, badgeMarginV);
                    break;
                case POSITION_BOTTOM_RIGHT:
                    lp.Gravity = GravityFlags.Right | GravityFlags.Bottom;
                    lp.SetMargins(0, 0, badgeMarginH, badgeMarginV);
                    break;
                case POSITION_CENTER:
                    lp.Gravity = GravityFlags.Center;
                    lp.SetMargins(0, 0, 0, 0);
                    break;
                default:
                    break;
            }

            LayoutParameters = lp;
        }

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

        /**
         * Is this badge currently visible in the UI?
         *
         */
        public override bool IsShown
        {
            get
            {
                return isShown;
            }
        }

        /**
         * Returns the positioning of this badge.
         *
         * one of POSITION_TOP_LEFT, POSITION_TOP_RIGHT, POSITION_BOTTOM_LEFT, POSITION_BOTTOM_RIGHT, POSTION_CENTER.
         *
         */
        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, POSTION_CENTER.
         *
         */
        public void setBadgePosition(int layoutPosition)
        {
            this.badgePosition = layoutPosition;
        }

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

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

        /**
         * 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.badgeMarginH = badgeMargin;
            this.badgeMarginV = badgeMargin;
        }

        /**
         * Set the horizontal/vertical margin from the target View that is applied to this badge.
         *
         * @param horizontal margin in pixels.
         * @param vertical margin in pixels.
         */
        public void setBadgeMargin(int horizontal, int vertical)
        {
            this.badgeMarginH = horizontal;
            this.badgeMarginV = vertical;
        }

        /**
         * 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(Android.Graphics.Color badgeColor)
        {
            this.badgeColor = badgeColor;
            badgeBg = getDefaultBackground();
        }

        private int DipToPixels(int dip)
        {
            Resources r =Resources;
            float px = TypedValue.ApplyDimension(ComplexUnitType.Dip, dip, r.DisplayMetrics);
            return (int)px;
        }
    }
}

使用方法:

    [Activity(Label = "BadgeActivity", MainLauncher = true)]
    public class BadgeActivity : Activity
    {
        private ZsCMS.Dorid.UI.BadgeView bv;
        protected override void OnCreate(Bundle savedInstanceState)
        {
            base.OnCreate(savedInstanceState);
            SetContentView(Resource.Layout.Badge);

            View buttion= FindViewById(Resource.Id.button1);
            bv = new UI.BadgeView(this, buttion);
            bv.Text = "600";
            bv.Show();

            buttion.Click += Buttion_Click;
            // Create your application here
        }

        private int i = 0;
        private void Buttion_Click(object sender, EventArgs e)
        {
            bv.Text = (++i).ToString();
        }
    }
时间: 2024-10-26 14:46:12

xamarin.android 给View控件 添加数字提醒效果-BadgeView的相关文章

xamarin android——数据绑定到控件(三)

如果当前活动中,只存在一个listview视图,可以借助ListActivity快速的实现一个列表,即当前Activity继承ListActivity.在OnCreate方法中简单的两行代码,就可以创建一个用户列表. string[] items = new string[]{ "列表 1","列表 2","列表 3","列表 4","列表 5","列表 6","列表 7&qu

xamarin android——数据绑定到控件(四)

本文为通过自定义列表适配器定义ListView,以上文为基础,基于ListActivity. 定义列表项布局,包含一个图片显示,标题和描述 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="80dip"> <ImageV

xamarin android——数据绑定到控件(一)

mono for android 中光标由ICursor 接口标识,该接口公开了操作结果数据集的所有方法.光标的使用非常消耗系统资源,所以不使用时应该光比光标.可以通过StartManagingCursor方法允许应用程序管理光标.示例中通过spinner显示用户浏览网址的历史记录,历史记录通过系统提供的内容提供器获取数据,更多内容提供器参考Android 开发文档http://developer.android.com/reference/android/provider/package-su

android 设置View控件的全局样式和风格

android开发部中,不可避免的要设定某一类按钮的按压,点击,聚焦等状态,通常对于这一类问题而言,最原始的方式就是在布局文件中亲自设定,然而对于一个比较大型的项目而言,这种方式造成的可维护性不是很好,因此要尽量做到代码重用. android项目中通常有3个设置样式的资源文件夹 values values-11 values-14 这三个对应不同平台的sdk版本的样式,对于android开发中兼容问题而言,要做到"让最新的api运行在最新的android sdk中",这是非常好的一种行

Android 自定义View控件

一.简介 在自定义View时,我们通常会重写onDraw()方法来绘制View的显示内容.如果,该View还需要使用wrap_content属性,那么还必须重写onMeasure()方法.另外,通过自定义attrs属性,还可以设置新的属性配置值. 在View中通常有以下一些比较重要的回调方法: onFinisInflate():从XML加载组件后回调: onSizeChanged():组件大小改变时回调: onMeasure():回调该方法来进行测量: onLayout():回调该方法来确定显示

Android自定义View控件

转自:http://blog.csdn.net/lvwenbo0107/article/details/50542597 写的够详细了 为什么要自定义控件 1.特定的显示风格. 2.处理特有的用户交互.(textView支持一些滑动功能) 3.优化我们的布局.(嵌套布局绘制比较慢) 4.封装.(tab页按钮不好看) 如何自定义控件 1.自定义属性声明与获取. 2.测量onMeasure. 3.布局onLayout(ViewGroup才需要) 4.绘制onDraw 5.onTouchEvent 6

Xamarin.Android之Picker控件关闭可编辑状态

在使用NumberPicker的时候,出现直接弹出键盘的情况,解决办法: picker.DescendantFocusability=DescendantFocusability.BlockDescendants; 另外在NumberPicker的使用过程中,还有两个几个问题: NumberPicker的MinValue和MaxValue表示的最小值和最大值,并不是实际显示的值,也就是说NumberPicker不是一个只显示Number的控件,可以显示任意的字符 picker.SetDispla

想给UIVIew上控件添加一些动画效果

如果你还不知道怎样让一张图片缓缓滑动,渐渐消失,或者是在原地翻滚,不知道怎样让一个窗口弹出的时候有一点抖动的效果不那么僵硬,那正好,今儿在下总结的内容可能刚好能帮你实现你想要的效果(⊙o⊙)哦. 首先说一下什么是动画效果,动画效果有哪些好处吧: 这里所说的动画绝对不是你在电视上看到的,有剧情的那种(当然这句可能是废话),而是为了增加用户的体验感,通过对控件的属性或者layer进行一些处理达到美化界面的效果,主要是让界面看起来更加的生动,不会太枯燥.想象一下,你在用读书软件时候的翻页效果,就能被称

xamarin android——数据绑定到控件(二)

本示例为通过媒体内容提供器获取本机中的图片显示在Gallery中. 活动中简单的初始化代码 private void InitGallery() { Gallery gallery = FindViewById<Gallery> (Resource.Id.gallery); gallery.Adapter = new ImageAdapter (this); } ImageAdapter 类为自己定义的适配器,继承BaseAdapter类,其中核心代码为GetView方法.BaseAdapte