How to remove the top and bottom space on textview of Android

前端 未结 14 1937
执笔经年
执笔经年 2020-11-28 04:58

When I include the below XML to layout file, I can see the below image. If you see it, you could realize that the TextView has top and bot

14条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-11-28 05:41

    I faced the same problem. Here's a good answer: How to align the text to top of TextView?

    But code is little unfinished and don't support all font sizes. Change the line

    int additionalPadding = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 5, getContext().getResources().getDisplayMetrics());
    

    to

    int additionalPadding = getTextSize() - getLineHeight();
    

    Complete C# code (mono) removes top offset:

    public class TextControl : TextView {
        public TextControl (Context context) : base (context)
        {
            SetIncludeFontPadding (false);
            Gravity = GravityFlags.Top;
        }
    
        protected override void OnDraw (Android.Graphics.Canvas canvas)
        {
            if (base.Layout == null)
                return;
    
            Paint.Color = new Android.Graphics.Color (CurrentTextColor);
            Paint.DrawableState = GetDrawableState ();
    
            canvas.Save ();
    
            var offset = TextSize - LineHeight;
            canvas.Translate (0, offset);
    
            base.Layout.Draw (canvas);
    
            canvas.Restore ();
        }
    }
    

提交回复
热议问题