How do I put a border around an Android textview?
If you wants to see text view as 3D view as we seen in Microsoft power point 3d texts. This example demonstrate about how do I put a border around an Android text view.
Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project.
Step 2 − Add the following code to res/layout/activity_main.xml.
In the above code we have taken one text view with background as border so we need to create a file in drawable as boarder.xml and add the following content.
In the above code we have taken shape as root tag and given shape is rectangle and added width and padding for shape.
Step 3 − Add the following code to src/MainActivity.java
Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click Runicon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen −
Как поместить рамку вокруг текстового представления Android?
Вы можете установить фигуру, которая может быть выделена (прямоугольник) в качестве фона для представления.
И прямоугольник drawable back.xml(помещается в папку res/drawable):
Вы можете использовать @android:color/transparent для сплошного цвета, чтобы иметь прозрачный фон. Вы также можете использовать отступы для ветки текста от границы. для получения дополнительной информации см.: http://developer.android.com/guide/topics/resources/drawable-resource.html
Позвольте мне подвести несколько различных (непрограммных) методов.
Используя форму, пригодную для рисования
Сохраните следующее в виде XML файла в вашей папке (например, my_border.xml):
Затем просто установите его в качестве фона для вашего TextView:
- Shape Drawable (Android docs)
- Советы и рекомендации для разработчиков Android: XML-чертежи (часть I)
Использование 9-патча
9-патч — растягиваемое фоновое изображение. Если вы создадите изображение с рамкой, это даст вашему TextView границу. Все, что вам нужно сделать, это сделать изображение, а затем установить его в фоновом режиме в TextView.
Вот некоторые ссылки, которые покажут, как сделать 9-патч-образ:
- Нарисуйте 9-патч
- Простой генератор Nine-patch
- Простой справочник по 9-патчу для Android-интерфейса пользователя
- Создание и использование 9-патч-изображений в Android
Что делать, если я просто хочу верхнюю границу?
Использование списка слоев
Вы можете использовать список слоев, чтобы складывать два прямоугольника друг над другом. Сделав второй прямоугольник чуть меньшим, чем первый прямоугольник, вы можете сделать эффект границы. Первый (нижний) прямоугольник — это цвет границы, а второй прямоугольник — цвет фона.
Настройка android:top=»2dp» смещает вершину (уменьшает ее) на 2dp. Это позволяет отобразить первый (нижний) прямоугольник, создавая эффект границы. Вы можете применить это к фону TextView так же, как и для shape drawable.
Вот еще несколько ссылок о списках слоев:
- Понимание списка < layer-list для Android >
- Как сделать нижнюю границу в выделенной форме XML-селектором?
- Создавать границы на представлении android в drawable xml с трех сторон?
Использование 9-патча
Вы можете просто сделать изображение с 9 патчами с одной границей. Все остальное такое же, как описано выше.
Использование представления
Это своего рода трюк, но он хорошо работает, если вам нужно добавить разделитель между двумя видами или границей в один текстовый файл.
Вот еще несколько ссылок:
- Как нарисовать линию в Android
- Как поместить горизонтальную линию делителя между редактированием текста в действии
- Как добавить горизонтальную линию 1px над представлением изображения в относительной компоновке?
Простым способом является добавление представления для вашего TextView. Пример для нижней граничной линии:
Для других границ направления, пожалуйста, отрегулируйте расположение разделителя.
Я решил эту проблему, расширив текст и нарисов границу вручную. Я даже добавил, что вы можете выбрать, будет ли точка пунктирной или пунктирной.
Надеюсь, это поможет кому-то:)
Я просто смотрел на похожий ответ — он мог быть выполнен с помощью Stroke и следующего переопределения:
Вы можете установить границу двумя способами. Один из них — с возможностью рисования, а второй — программный.
Использование Drawable
Я нашел лучший способ поместить границу вокруг TextView.
Используйте изображение с девятью патчами для фона. Это довольно просто, SDK поставляется с инструментом для создания 9-патча изображения, и он включает в себя абсолютно не кодирование.
В коде можно добавить что-то вроде этого:
Проверьте приведенную ниже ссылку, чтобы сделать закругленные углы http://androidcookbook.com/Recipe.seam?recipeId=2318
Выделенная папка под разрешением в проекте Android не ограничена растровыми изображениями (PNG или JPG файлами), но также может содержать формы, определенные в файлах XML.
Эти формы затем могут быть повторно использованы в проекте. Форма может быть использована для размещения границы вокруг макета. В этом примере показана прямоугольная рамка с изогнутыми углами. В выпадающей папке создается новый файл customborder.xml(в Eclipse используйте меню «Файл» и выберите «Создать», затем «Файл», в котором выбран тип выбранной папки в имени файла и нажмите «Готово» ).
Вводится XML, определяющий форму границы:
Атрибут android:shape установлен в прямоугольник (файлы формы также поддерживают овал, линию и кольцо). Rectangle — значение по умолчанию, поэтому этот атрибут может быть опущен, если он определен как прямоугольник. Подробную информацию о файле формы см. В документации по форматам на http://developer.android.com/guide/topics/resources/drawable-resource.html#Shape.
Углы элементов устанавливают углы прямоугольника для округления. На каждом углу можно задать другой радиус (см. Ссылку на Android).
Атрибуты дополнения используются для перемещения содержимого представления, к которому применяется форма, для предотвращения совпадения содержимого границы.
Цвет рамки здесь установлен на светло-серый (CXCCC шестнадцатеричное значение RGB).
Формы также поддерживают градиенты, но здесь они не используются. Опять же, просмотрите ресурсы Android, чтобы узнать, как определяется градиент. Форма применяется к простыне с помощью android:background=»@drawable/customborder» .
В макете могут быть добавлены другие представления как обычно. В этом примере был добавлен один TextView, а текст белый (FFFFFF шестнадцатеричный RGB). Фон установлен на синий, плюс прозрачность, чтобы уменьшить яркость (значение A00000FF hexadecimal alpha RGB). Наконец, макет смещается с края экрана, помещая его в другой макет с небольшим количеством отступов. Таким образом, полный файл макета:
Как поместить рамку вокруг символа в textview
android: background = «@ drawable / your_fileName»

CompileSdkVersion 26 (Android 8.0), minSdkVersion 21 (Android 5.0), targetSdkVersion 26, реализация com.android.support:appcompat-v7:26.1.0, gradle: 4.1
Как поставить рамку вокруг текстового представления Android?
Используя Drawable
How to put a border around an Android TextView?
Is it possible to draw a border around an Android TextView ?
23 Answers 23
You can set a shape drawable (a rectangle) as background for the view.
And rectangle drawable back.xml (put into res/drawable folder):
You can use @android:color/transparent for the solid color to have a transparent background. You can also use padding to separate the text from the border. for more information see: http://developer.android.com/guide/topics/resources/drawable-resource.html
Let me summarize a few different (non-programmatic) methods.
Using a shape drawable
Save the following as an XML file in your drawable folder (for example, my_border.xml):
Then just set it as the background to your TextView:
Using a 9-patch
A 9-patch is a stretchable background image. If you make an image with a border then it will give your TextView a border. All you need to do is make the image and then set it to the background in your TextView.
Here are some links that will show how to make a 9-patch image:
What if I just want the top border?
Using a layer-list
You can use a layer list to stack two rectangles on top of each other. By making the second rectangle just a little smaller than the first rectangle, you can make a border effect. The first (lower) rectangle is the border color and the second rectangle is the background color.
Setting android:top=»2dp» offsets the top (makes it smaller) by 2dp. This allows the first (lower) rectangle to show through, giving a border effect. You can apply this to the TextView background the same way that the shape drawable was done above.
Here are some more links about layer lists:
Using a 9-patch
You can just make a 9-patch image with a single border. Everything else is the same as discussed above.
Using a View
This is kind of a trick but it works well if you need to add a seperator between two views or a border to a single TextView.
Here are some more links:
The simple way is to add a view for your TextView. Example for the bottom border line:
For the other direction borders, please adjust the location of the separator view.
![]()
I have solved this issue by extending the textview and drawing a border manually. I even added so you can select if a border is dotted or dashed.
And the border class:
Hope this helps someone 🙂
![]()
Simplest solution I’ve found (and which actually works):
You can set the border by two methods. One is by drawable and the second is programmatic.
Using Drawable
![]()
![]()
I was just looking at a similar answer— it’s able to be done with a Stroke and the following override:
You can add something like this in your code:
![]()
I found a better way to put a border around a TextView.
Use a nine-patch image for the background. It’s pretty simple, the SDK comes with a tool to make the 9-patch image, and it involves absolutely no coding.
![]()
The drawable folder, under res, in an Android project is not restricted to bitmaps (PNG or JPG files), but it can also hold shapes defined in XML files.
These shapes can then be reused in the project. A shape can be used to put a border around a layout. This example shows a rectangular border with curved corners. A new file called customborder.xml is created in the drawable folder (in Eclipse use the File menu and select New then File, with the drawable folder selected type in the file name and click Finish).
The XML defining the border shape is entered:
The attribute android:shape is set to rectangle (shape files also support oval, line, and ring). Rectangle is the default value, so this attribute could be left out if it is a rectangle being defined. See the Android documentation on shapes at http://developer.android.com/guide/topics/resources/drawable-resource.html#Shape for detailed information on a shape file.
The element corners sets the rectangle corners to be rounded. It is possible to set a different radius on each corner (see the Android reference).
The padding attributes are used to move the contents of the View to which the shape is applied, to prevent the contents overlapping the border.
The border color here is set to a light gray (CCCCCC hexadecimal RGB value).
Shapes also support gradients, but that is not being used here. Again, see the Android resources to see how a gradient is defined. The shape is applied to the laypout using android:background=»@drawable/customborder» .
Within the layout other views can be added as normal. In this example, a single TextView has been added, and the text is white (FFFFFF hexadecimal RGB). The background is set to blue, plus some transparency to reduce the brightness (A00000FF hexadecimal alpha RGB value). Finally the layout is offset from the screen edge by placing it into another layout with a small amount of padding. The full layout file is thus:
Android TextView Border
To draw a border around TextView, you can use background attribute of the TextView widget and assign a shape to it. The shape is such that the stroke on the shape outline appears as border.

The sample code to draw border for TextView is
You have to create the following drawable file in res/drawable/ folder.