- How to right-align text in an Android TextView or EditText?
- 5 Answers 5
- Right align text in android TextView
- 20 Answers 20
- How do I center text horizontally and vertically in a TextView?
- 69 Answers 69
- Android TextView: выравнивание текста по ширине
- 26 ответов
- ОБНОВЛЕНО
- Выравнивание текста справа в Android TextView
- 18 ответов
How to right-align text in an Android TextView or EditText?
I have an EditText in my application. I want to align the text in it to the right instead of the default left. I tried adding
but this doesn’t seem to work. any other suggestions please?
5 Answers 5
You should use android:gravity=»right» . layout_gravity is for the view (EditText) alignment against the container.
You may use android:layout_alignParentRight=»true» to align the EditText’s right edge to its parent’s right edge. Also, if you really want to use the layout_gravity or gravity attributes, check out this article that discusses the proper use of them.
You can jst set property for edit text in property window i.e. Gravity to right or by adding code of lin e in xml file of UI : android:gravity=»right»
layout_gravity means that you are specifying the layouts attribute, not the element inside. In some conditions, such as layout_width and layout_height is wrap_content, layout specifications can give what you want about the element inisde your layout, since the boundries of the layout and the element (not elements) are the same..
use layout width and height as wrap content inside relative layout :
Источник
Right align text in android TextView
I have a TextView in my application. I want to align the text in it to the right. I tried adding:
But this doesn’t work for me.
What might I be doing wrong?
20 Answers 20
I think that you are doing this: android:layout_width = «wrap_content»
If this is the case, do this: android:layout_width = «match_parent»
In general, android:gravity=»right» is different from android:layout_gravity=»right» .
The first one affects the position of the text itself within the View, so if you want it to be right-aligned, then layout_width= should be either «fill_parent» or «match_parent» .
The second one affects the View’s position inside its parent, in other words — aligning the object itself (edit box or text view) inside the parent view.
The better solution is the one that is the most simple, and the one that does less modification in your code behaviour.
What if you can solve this problem only with 2 Properties on your TextView ?
Instead of needing to change your LinearLayout Properties that maybe can alter the behaviour of LinearLayout childs?
Using this way, you do not need to change LinearLayout properties and behaviour, you only need to add the two following properties to your target TextView :
What would be better to change only your target to solve your solution instead of having a chance to cause another problem in the future, modifying your target father? think about it 🙂
Источник
How do I center text horizontally and vertically in a TextView?
How do I center the text horizontally and vertically in a TextView , so that it appears exactly in the middle of the TextView in Android ?
69 Answers 69
I’m assuming you’re using XML layout.
You can also use gravity center_vertical or center_horizontal according to your need.
and as @stealthcopter commented in java: .setGravity(Gravity.CENTER);
This will do the trick
You can also set it up dynamically using:
This works when used with a RelativeLayout where the layout’s height & width are set to wrap_content.
You can also use the combination:
Then, if textview width is more than «fill_parent» the text will still be aligned to left (not centered as with gravity set only to «center»).
There are two ways of doing this.
The first in the XML code. You need to pay attention at the Gravity Attribute. You also can find this attribute in the Graphic Editor; it may be easier than the XML EDITOR.
For your specific scenario, the values of gravity will be:
In the graphical editor you will find all the possible values, even see their results.
If you are using TableLayout make sure to set the gravity of the TableRows to center, too. Otherwise it will not work. At least it didn’t work with me until I set the gravity of the TableRow to center.
For example, like this:
You need to set TextView Gravity (Center Horizontal & Center Vertical) like this:
And dynamically using:
which is better than,
at least for formatting text.
For Linear Layout: In XML use something like this
To do this at run time use something like this in your activity
For Relative Layout: in XML use some thing like this
To do this at run time use something like this in your activity
Use in the XML file.
Layout file
Use this inside the Java class
Use this for relative layout
and for other layout
If the TextView’s height and width are wrap content then the text within the TextView always be centered. But if the TextView’s width is match_parent and height is match_parent or wrap_content then you have to write the below code:
For RelativeLayout:
For LinearLayout:
While using gravity works for TextView, there’s an alternate method implemented in API level 17 —
Don’t know the difference, but it works too. However only for API level 17 or higher.
In RelativeLayout , it will be nice with it.
And another Button and anything else you can add.
The following works nicely for me.
Easiest way (which is surprisingly only mentioned in comments, hence why I am posting as an answer) is:
You can just set the gravity of your textview into CENTER .
If you are trying to center text on a TableRow in a TableLayout, here is how I achieved this:
If you are using Relative Layout:
If you are using LinearLayout
Here is my answer that I had used in my app. It shows text in center of the screen.
TextView gravity works as per your parent layout.
LinearLayout:
If you use LinearLayout then you will find two gravity attribute android:gravity & android:layout_gravity
android:gravity : represent layout potion of internal text of TextView while android:layout_gravity : represent TextView position in parent view.
If you want to set text horizontally & vertically center then use below code this
RelativeLayout:
Using RelativeLayout you can use below property in TextView
android:gravity=»center» for text center in TextView.
android:gravity=»center_horizontal» inner text if you want horizontally centered.
android:gravity=»center_vertical» inner text if you want vertically centered.
android:layout_centerInParent=»true» if you want TextView in center position of parent view. android:layout_centerHorizontal=»true» if you want TextView in horizontally center of parent view. android:layout_centerVertical=»true» if you want TextView in vertically center of parent view.
Источник
Android TextView: выравнивание текста по ширине
Как добиться выравнивания текста в TextView (с выравниванием текста слева и справа)?
Я нашел возможное решение здесь, но оно не работать (даже если вы измените vertical-center на center_vertical и т. д.).
26 ответов
Для выравнивания текста в android я использовал WebView
Я пока не могу загрузить изображения, чтобы доказать это, но «у меня это работает».
TextView в Android O предлагает полное выравнивание (новое типографское выравнивание).
Вам просто нужно сделать это:
Котлин
Java
XML
По умолчанию: JUSTIFICATION_MODE_NONE ( none в xml).
ОБНОВЛЕНО
Мы создали для этого простой класс. В настоящее время есть два метода достижения того, что вы ищете. Оба требуют НЕТ WEBVIEW и ПОДДЕРЖИВАЕТ SPANNABLES .
ПОДДЕРЖКА : Android 2.0 до 5.X
НАСТРОЙКА
Вы можете использовать проект JustifiedTextView для Android в github. это настраиваемый вид, имитирующий для вас выровненный по ширине текст. Он поддерживает Android 2.0+ и языки справа налево.
Для этого я пишу базу виджетов на собственном текстовом представлении.
Я нашел способ решить эту проблему, но это может быть не очень изящно, но эффект неплохой.
Его принцип заключается в замене пробелов в каждой строке на ImageSpan фиксированной ширины (цвет прозрачный).
Очень просто Мы можем сделать это в файле xml
Вот как я это сделал, на мой взгляд, самый элегантный способ. При использовании этого решения единственное, что вам нужно сделать в макетах:
- добавить дополнительную декларацию xmlns
- измените пространство имен исходного текста TextView s с android на новое пространство имен
- замените TextView на x.y.z.JustifiedTextView
Вот код. Прекрасно работает на моих телефонах (Galaxy Nexus Android 4.0.2, Galaxy Teos Android 2.1). Не стесняйтесь, конечно, заменить мое имя пакета вашим.
/assets/justified_textview.css :
/res/values/attrs.xml :
/res/layout/test.xml :
/src/net/bicou/myapp/widget/JustifiedTextView.java :
Нам нужно настроить рендеринг на программное обеспечение, чтобы получить прозрачный фон на Android 3+. Отсюда и проблема для более старых версий Android.
Надеюсь это поможет!
PS: пожалуйста, обратите внимание, что может быть полезно добавить это ко всей вашей деятельности на Android 3+, чтобы получить ожидаемое поведение:
android:hardwareAccelerated=»false»
Хотя вы все еще не полностью выровненный по ширине текст, теперь вы можете сбалансировать длину строк с помощью android:breakStrategy=»balanced» , начиная с API 23.
Выравнивание текста Android для TextView XML
Просто Android с выравниванием текста по ширине в XML. Вы можете просто реализовать в виджете textview.
По умолчанию android:justificationMode=»none»
Я пишу свой собственный класс для решения этой проблемы. Вот вам просто нужно вызвать статическую функцию выравнивания, которая принимает два аргумента.
- Текстовый объект просмотра
- Ширина содержимого (общая ширина вашего текстового представления)
FILL_HORIZONTAL эквивалентно CENTER_HORIZONTAL . Вы можете увидеть этот фрагмент кода в исходном коде textview:
Для этой проблемы существует CustomView, это настраиваемое текстовое представление поддерживает Justified Text View.
Добавьте указанный выше класс в папку src и используйте этот пример кода для добавления в свой макет:
Просто импортируйте два файла «TextJustifyUtils.java» и «TextViewEx.java» в свой проект.
Теперь, если вы используете обычный textView, например:
Определите переменную и установите для параметра justify значение true,
Обоснование содержания TextView: Его простые ребята просто используют android: justificationMode = «inter_word» в вашем теге TextView.
Просто попробуйте это,
Надеюсь на эту помощь!
Я думаю, что есть два варианта:
Используйте что-то вроде Pango, который специализируется на этом через NDK, и визуализируйте текст в OpenGL или на другой поверхности.
Android пока не поддерживает полное обоснование. Мы можем использовать Webview и выравнивать HTML вместо использования textview. Это прекрасно работает. Если вам непонятно, не стесняйтесь спрашивать меня 🙂
На android, чтобы выровнять текст по левому краю и не иметь усечения цвета фона, попробуйте это, у меня это сработало, давая согласованные результаты на android, ff, т.е. и chrome, но вы должны измерить пространство, которое осталось между текстом при расчете заполнения.
Хакерством является padding-right:1000px; , который сдвигает текст в крайнее левое положение.
Любая попытка сдвинуть код влево или по ширине в css или html приводит к созданию фона только половинной ширины.
Эта строка кода сделает ваш текст оправданным
Вы можете использовать justificationMode как inter_word в xml. Вы должны помнить, что этот атрибут доступен для уровня API 26 и выше. Для этого вы можете назначить targetApi как o. Полный код приведен ниже.
Попробуйте использовать RelativeLayout > (обязательно fill_parent), затем просто добавьте android:layout_alignParentLeft=»true» и
android:layout_alignParentRight=»true» к элементам, которые вы хотели бы видеть снаружи ВЛЕВО и ВПРАВО.
Источник
Выравнивание текста справа в Android TextView
у меня есть TextView в моем приложении. Я хочу выровнять текст справа. Я попытался добавить:
но это не работает для меня.
что я могу делать неправильно?
18 ответов
Я думаю, что вы делаете это: android:layout_width = «wrap_content»
Если это так, сделайте следующее: android:layout_width = «match_parent»
В общем, android:gravity=»right» отличается от android:layout_gravity=»right» .
первый влияет на положение самого текста в представлении, поэтому, если вы хотите, чтобы он был выровнен по правому краю, то layout_width= должно быть «fill_parent» или «match_parent» .
второй влияет на положение представления внутри его родителя, другими словами-выравнивание самого объекта (поле редактирования или текстовое представление) внутри родительского представления.
лучшим решением является тот, который является самым простым, и тот, который делает меньше изменений в вашем поведении кода.
что делать, если вы можете решить эту проблему только с 2 свойства TextView ?
вместо того, чтобы изменить свой LinearLayout свойства, которые, возможно, могут изменить поведение LinearLayout Чайлдс?
используя этот путь, вам не нужно изменить LinearLayout свойства и поведение, нужно только добавить два следующих свойства для вашей цели TextView :
что было бы лучше изменить только вашу цель, чтобы решить ваше решение, вместо того, чтобы иметь шанс вызвать другую проблему в будущем, изменяя ваш целевой отец? подумайте об этом 🙂
android:layout_gravity используется для выравнивания текстового представления относительно родительского макета. android:gravity используется для выравнивания текста внутри текстового представления.
вы уверены, что пытаетесь выровнять текст внутри текстового представления справа или хотите переместить само текстовое представление вправо по отношению к родительскому макету или пытаетесь достичь обоих
убедитесь, что вы не используете android:layout_width=»wrap_content» Если это так, то он не сможет установить гравитацию, потому что у вас недостаточно места для выравнивания текста. Вместо этого используйте android:layout_width=»fill_parent»
Источник