Skip to content Skip to sidebar Skip to footer

Remove Space Between Stacked Textviews

I have a vertical LinearLayout with two TextView inside it. The former contains a static text property (it's text never change) and the last contains a regressive timer. The image

Solution 1:

Try using negative margins. It may take a bit of playing with the numbers to get it right, but I've done it before and it worked out well.

android:layout_marginTop="-5dp"

Solution 2:

By default, a TextView includes some padding to leave space for accent characters. You can turn that off with:

 android:includeFontPadding="false"

or

 textView.setIncludeFontPadding(false)

Solution 3:

Make baseline of the text equal to the bottom of the TextView.

publicclassBaselineTextViewextendsTextView {

    publicBaselineTextView(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    @OverrideprotectedvoidonDraw(Canvas canvas) {
        intyOffset= getHeight() - getBaseline();
        canvas.translate(0, yOffset);
        super.onDraw(canvas);
    }

}

NOTE: To avoid chopping off descenders call setClipChildren(false) on your TextView's parent ViewGroup (android:clipChildren="false" in XML).

Solution 4:

If you set includeFontPadding to false it helps.

android:includeFontPadding="false"

but if you know you don't have any descenders because you set

android:textAllCaps="true"

or you know there are no characters which have descender, you can make a custom TextView and set the height to the baseline.

publicclassExTextViewextendsTextView {

    publicExTextView(Context context) {
        this(context, null);
    }

    publicExTextView(Context context, @Nullable AttributeSet attrs) {
        this(context, attrs, 0);
    }

    publicExTextView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    @TargetApi(Build.VERSION_CODES.LOLLIPOP)
    publicExTextView(Context context, @Nullable AttributeSet attrs, int defStyleAttr, int defStyleRes) {
        super(context, attrs, defStyleAttr, defStyleRes);
    }

    @OverrideprotectedvoidonDraw(Canvas canvas) {
        setHeight(getBaseline());  // <--- Shrink size to baselinesuper.onDraw(canvas);
    }
}

The source code is included in my UiComponents test app. https://github.com/landenlabs/UiComponents

Solution 5:

negative margins will do the trick

Post a Comment for "Remove Space Between Stacked Textviews"