- Android: TextView: удаление интервала и отступов сверху и снизу
- ОТВЕТЫ
- Ответ 1
- Ответ 2
- Ответ 3
- Ответ 4
- Ответ 5
- Ответ 6
- Ответ 7
- Ответ 8
- Ответ 9
- Ответ 10
- Ответ 11
- Ответ 12
- Ответ 13
- Ответ 14
- Ответ 15
- Android: TextView: Remove spacing and padding on top and bottom
- [Snackbar] Can’t change top and bottom padding of snackbar’s text view #1179
- Comments
- MarkNjunge commented Apr 3, 2020
- hunterstich commented Apr 6, 2020
- MarkNjunge commented Apr 6, 2020
- DKKovalev commented Apr 10, 2020
- DanielMartinus commented May 27, 2020 •
- DanielMartinus commented May 27, 2020 •
- Snackbar.java
- SnackbarContentLayout
Android: TextView: удаление интервала и отступов сверху и снизу
Когда у меня есть TextView с \n в тексте, на право у меня есть два singleLine TextView с, один под другим, без интервала между ними. Я установил следующее для всех трех TextView .
Первая строка левого TextView идеально TextView с верхней правой TextView .
Вторая строка левого TextView немного выше, чем вторая строка нижнего правого TextView .
Кажется, что есть некоторые скрытые отступы сверху и снизу TextView . Как я могу удалить это?
ОТВЕТЫ
Ответ 1
или в XML это будет:
Задайте, включает ли TextView дополнительное верхнее и нижнее отступы, чтобы освободить место для акцентов, которые превышают нормальное восхождение и спуск. Значение по умолчанию — true.
Ответ 2
Я чувствую твою боль. Я пробовал каждый ответ выше, включая setIncludeFontPadding в false, который ничего не сделал для меня.
Мое решение? layout_marginBottom=»-3dp» на TextView дает вам решение для нижней части, BAM!
Хотя, -3dp на layout_marginTop терпит неудачу. тьфу.
Ответ 3
Я много искал правильный ответ, но нигде не мог найти ответ, который мог бы точно удалить все отступы из TextView , но, наконец, после прохождения официального документа удалось обойти однострочные тексты.
Добавление этих двух строк в TextView xml сделает всю работу.
Первый атрибут удаляет отступы, зарезервированные для акцентов, а второй атрибут удаляет интервал, зарезервированный для поддержания надлежащего пространства между двумя строками текста.
Не добавляйте lineSpacingExtra=»0dp» в многострочное TextView, так как это может сделать внешний вид неуклюжим
Ответ 4
Это тоже меня раздражало, и ответ, который я нашел, заключался в том, что в самом шрифте есть дополнительное пространство, а не TextView. Это довольно раздражает, исходя из фона публикации документов, ограниченного количества контроля над Android над типографскими элементами. Я бы рекомендовал использовать пользовательский шрифт (например, Bitstream Vera Sans, который лицензирован для перераспределения), который может не иметь этой проблемы. Однако я не уверен, действительно ли это делает.
Ответ 5
Я удаляю интервал в моем пользовательском представлении — NoPaddingTextView.
Ответ 6
С помощью дополнительного ImageView мы можем установить TextView в исходное положение, выровненное с ImageView, и установить android:baselineAlignBottom в ImageView равным true, что сделает базовую линию ImageView снизу. Другие представления могут выравниваться, используя нижнюю часть ImageView, которая сама по себе совпадает с базовой линией TextView.
Это, однако, фиксирует только дно прокладки, а не верх.
Ответ 7
Я думаю, что эта проблема может быть решена следующим образом:
Хотя строка специальных символов в rightLowerText выглядит немного выше второй строки leftText, их базовые линии выравниваются.
Ответ 8
Поскольку мое требование переопределяет существующий textView get from findViewById(getResources().getIdentifier(«xxx», «id», «android»)); , поэтому я не могу просто попробовать onDraw() другого ответа.
Но я просто выясню правильные шаги для исправления моей проблемы, вот окончательный результат от Layout Inspector:
Так как я хотел просто удалить верхние пространства, поэтому мне не нужно выбирать другой шрифт для удаления нижних пространств.
Вот критический код для его исправления:
Первый ключ — это настраиваемый шрифт «fonts/myCustomFont.otf», который имеет место внизу, но не сверху, вы можете легко понять это с помощью открытого файла otf и щелкнуть любой шрифт в android Studio:
Как вы можете видеть, курсор внизу имеет дополнительный интервал, но не сверху, поэтому он исправил мою проблему.
Второй ключ , вы не можете просто пропустить любой код, иначе он может не работать. Это причина, по которой вы можете обнаружить, что некоторые люди отмечают, что ответ работает, а некоторые другие люди отмечают, что он не работает.
Покажем, что произойдет, если я удалю один из них.
Без setPadding(0, 0, 0, 0); :
Без 3 из них (т.е. оригинала):
Ответ 9
Вы можете попробовать использовать этот атрибут (ConstraintLayout): layout_constraintBaseline_toBaselineOf
Приложение: layout_constraintBaseline_toBaselineOf = «@+id/TextView»
Ответ 10
Если вы используете AppCompatTextView (или начиная с API 28 и далее), вы можете использовать комбинацию этих двух атрибутов для удаления пробела в первой строке:
XML
Котлин
Ответ 11
Простой метод работал:
Если это не сработало, попробуйте добавить этот код выше:
Если вам нужна многострочная информация, возможно, вам нужно будет точно рассчитать высоту верхнего и нижнего отступов с помощью временной строки TextView (до и после удаления отступов), а затем применить результат уменьшения высоты с отрицательным заполнением или какой-либо Ghost Layout с переводом Y. Лол
Ответ 12
Единственное, что сработало
Ответ 13
Возможно, вы захотите выполнить выравнивание нижней части левого текстового представления в нижней части второго правого текстового представления.
Ответ 14
Насколько мне известно, это присуще большинству виджетов, а количество «отступов» отличается от производителей телефонов. Это заполнение — это действительно пустое пространство между границей изображения и изображением в 9 файлах патча.
Например, на моем Droid X виджеты spinner получают лишнее пробел, чем кнопки, что делает его неудобным, когда у вас есть прядильный ролик с кнопкой, но на моей женской телефоне одно и то же приложение не имеет такой же проблемы и отлично смотрится!
Единственное, что я хотел бы сделать, это создать ваши собственные файлы исправлений и использовать их в вашем приложении.
Ahhh боли, которые являются Android.
Отредактировано: Уточнить дополнение к пробелу.
Ответ 15
Кажется, что фоновое изображение EditText имеет несколько прозрачных пикселей, которые также добавляют дополнение.
Решением является изменение фона по умолчанию EditText на что-то другое (или ничего, но фон для EditText, вероятно, неприемлем). Это можно сделать установкой андроида: фоновым атрибутом XML.
Источник
Android: TextView: Remove spacing and padding on top and bottom
Posted by: admin November 20, 2017 Leave a comment
When I have a TextView with a \n in the text,, on the right I have two singleLine TextView s, one below the other with no spacing in between. I have set the following for all three TextView s.
The first line of the left TextView lines up perfectly with the top right TextView . The second line of the left TextView is a little higher than the second line of the bottom right TextView .
It seems that there is some kind of hidden padding on the top and the bottom of the TextView s. How can I remove that?
or in XML this would be:
Set whether the TextView includes extra top and bottom padding to make room for accents that go above the normal ascent and descent. The default is true.
I feel your pain. I’ve tried every answer above, including the setIncludeFontPadding to false, which did nothing for me.
My solution? layout_marginBottom=»-3dp» on the TextView gives you a solution for the bottom,
BAM!
Although, -3dp on layout_marginTop fails….ugh.
I searched a lot for proper answer but no where I could find an Answer which could exactly remove all the padding from the TextView , but finally after going through the official doc got a work around for Single Line Texts
Adding these two lines to TextView xml will do the work.
First attribute removes the padding reserved for accents and second attribute removes the spacing reserved to maintain proper space between two lines of text.
Make sure not to add lineSpacingExtra=»0dp» in multiline TextView as it might make the appearance clumsy
This annoyed me too, and the answer I found was that there is actually additional space in the font itself, not the TextView. It is rather irritating, coming from a document publishing background, the limited amount of control you have with Android over typographic elements. I’d recommend using a custom typeface (such as Bitstream Vera Sans, which is licensed for redistribution) that may not have this issue. I’m not sure specifically whether or not it does, though.
With an extra ImageView we can set the TextView to be baseline aligned with the ImageView and set the android:baselineAlignBottom on the ImageView to true, which will make the baseline of ImageView to bottom. Other views can align itself using the bottom of the ImageView which itself is the same as the TextView’s baseline.
This however only fixes the padding bottom not the top.
I think this problem can be solved in this way:
Those are the results:
Though the line of special characters in rightLowerText looks a little bit higher than the second line of leftText, their baselines are stilled aligned.
I remove the spacing in my custom view — NoPaddingTextView.
You might want to try aligning the bottom of the left text view with the bottom of the 2nd right text view.
To my knowledge this is inherent to most widgets and the amount of “padding” differs among phone manufacturers. This padding is really white space between the image border and the image in the 9 patch image file.
For example on my Droid X, spinner widgets get extra white space than buttons, which makes it look awkward when you have a spinner inline with a button, yet on my wife’s phone the same application doesn’t have the same problem and looks great!
The only suggestion I would have is to create your own 9 patch files and use them in your application.
Ahhh the pains that are Android.
Edited: Clarify padding vs white space.
It seems that the background image of EditText has some transparent pixels which also add padding.
A solution is to change the default background of EditText to something else (or nothing, but no background for a EditText is probably not acceptable). That’s can be made setting android:background XML attribute.
Since my requirement is override the existing textView get from findViewById(getResources().getIdentifier(«xxx», «id», «android»)); , so I can’t simply try onDraw() of other answer.
But I just figure out the correct steps to fixed my problem, here is the final result from Layout Inspector:
Since what I wanted is merely remove the top spaces, so I don’t have to choose other font to remove bottom spaces.
Here is the critical code to fixed it:
The first key is set custom font “fonts/myCustomFont.otf” which has the space on bottom but not on the top, you can easily figure out this by open otf file and click any font in android Studio:
As you can see, the cursor on the bottom has extra spacing but not on the top, so it fixed my problem.
The second key is you can’t simply skip any of the code, otherwise it might not works. That’s the reason you can found some people comment that an answer is working and some other people comment that it’s not working.
Let’s illustrated what will happen if I remove one of them.
Источник
[Snackbar] Can’t change top and bottom padding of snackbar’s text view #1179
Comments
MarkNjunge commented Apr 3, 2020
Description:
Setting 0dp changes the start and end padding but the top and bottom remain unchanged.
Setting android:paddingTop and android:paddingBottom has the same effect.
From the layout inspector
Expected behavior:
The top and bottom padding change, similar to start and end.
Source code:
Android API version: 29
Material Library version: 1.2.0-alpha05
Device: Android Emulator — Pixel 2
The text was updated successfully, but these errors were encountered:
hunterstich commented Apr 6, 2020
You can set your theme’s snackbarStyle with android:paddingTop and android:paddingBottom to achieve increase the padding.
Are you trying to remove all top and bottom padding?
MarkNjunge commented Apr 6, 2020
Yes, I’m trying to remove it.
DKKovalev commented Apr 10, 2020
Hi, i have the same issue, i want to remove extra top and bottom padding from text when it has more than one line:
DanielMartinus commented May 27, 2020 •
Same here indeed. Can’t remove the padding
There are huge paddings in the TextView in the screenshot above, I tried removing them with Widget.MaterialComponents.Snackbar.TextView but no luck.
The paddings seem twice as big when having a singleline: =
DanielMartinus commented May 27, 2020 •
I just went through the source and found a way of updating the padding of the Snackbar. I’ll explain the steps that I went through, see tl;dr at the end.
Snackbar.java
In Snackbar.java on line167 you can see it inflating one of two layouts:
R.layout.mtrl_layout_snackbar_include : R.layout.design_layout_snackbar_include
In those layouts you see almost two similar layouts, just different stylings and references. What they have in common though is the TextView and Button. The TextView is named: android:id=»@+id/snackbar_text»
However this snackbar_text isn’t used anywhere in snackbar.java but after some more investigation I found it’s used in SnackbarContentLayout referenced all over the place, but most importantly on line 163 in snackbar.java.
SnackbarContentLayout
Going into this SnackbarContentLayout I looked for snackbar_text which is assigned to messageView . Following this messageView you quickly find line124 where it’s doing a condition if the textview contains a single or multilines updating the bottom and top padding.
Following back where updateViewsWithinLayout is called from (line101) you see it’s choosing between a multiLineVPadding or singleLineVPadding.
Following multiLineVPadding you’ll see it assigned on line91
Finally looking up design_snackbar_padding_vertical_2lines you’ll see it has 24dp assigned.
Источник