- Antarix / layout_border_bottom
- This comment has been minimized.
- faizalumer commented Aug 29, 2014
- This comment has been minimized.
- sumitlahade commented Jul 16, 2017
- Tek Eye
- Drawable Folder
- Creating the Border Drawable
- Add the Border to a Layout
- Archived Comments
- Do you have a question or comment about this article?
- Как поместить границу вокруг Android textview?
- 16 ответов
- использование фигуры drawable
- использование 9-патч
- что, если я просто хочу верхнюю границу?
- Использование Drawable
- Android Border – Draw Android Textview Border
Antarix / layout_border_bottom
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode characters
xml version = » 1.0 » encoding = » utf-8 » ?> |
layer-list xmlns : android = » http://schemas.android.com/apk/res/android » > |
item > |
shape |
android : shape = » rectangle » > |
Set the border color of your layout here —> |
stroke android : width = » 1dp » android : color = » #3AFB03 »/> |
solid android : color = » #3AFB03 »/> |
shape > |
item > |
This is for border bottom but |
you can change this according to your need —> |
item android : bottom = » 4dp » > |
shape |
android : shape = » rectangle » > |
Set the background color of your layout here —> |
stroke android : width = » 1dp » android : color = » #000000 »/> |
solid android : color = » #000000 »/> |
shape > |
item > |
layer-list > |
This comment has been minimized.
Copy link Quote reply
faizalumer commented Aug 29, 2014
this is awesome. but i am wondering why would you use a bottom offset value of 4dp for the top layer, when the border width is only 1dp?
This comment has been minimized.
Copy link Quote reply
sumitlahade commented Jul 16, 2017
How to give margins from left and right to the border? I don’t want border to be end to end. Is there any solution ?
Источник
Tek Eye
The User Interface (UI) for an Android Application (App) must be easy to use, intuitive and pleasing to the eye. With Android Studio and the Software Development Kit (SDK) it is easy to generate screens, but the developer should add a little extra to make the interface attractive. Fortunately the SDK allows for enhancements to the UI using attributes on layouts and views. These attributes affect the UI appearence when a screen is displayed. The background attribute is one of the most versatile, it can be used to set colors, images, nine patch files and shapes. In this example project a simple Android shape is used to add a rectangular border with rounded corners to a layout file.
(This Android border tutorial assumes that Android Studio is installed; a basic App can be created and run; and code can be correctly copied into Studio. For this test App the Application name is called Layout Border and an Empty Activity is used. You are free to change this example for your own requirements. When entering code in Studio add import statements when prompted by pressing Alt-Enter.)
Drawable Folder
In an Android App project the drawable folder holds graphical resources (part of a wide range of Android resources that a project can have). Different types of drawables include image bitmaps (e.g. PNG or JPG) and XML definitions of shapes, colours and animations. Any drawable can be referenced from any screen. (In earlier versions of Android the res/drawable folder also stored an App’s launcher icon. Now launcher icons are located in the mipmap folders.) This screenshot example shows a drawable defining a horizontal line:
Creating the Border Drawable
Add a file called customborder.xml to the drawable folder. (In the Project explorer highlight the res/drawable folder. Use the context menu, normally right-click, or the File menu and select New then Drawable resource file. In the New Drawable Resource File dialog enter a File name of customborder. Set the Root element to shape. Click OK.. Click OK.) Code is added to define a rectangle that has rounded corners, some padding and a solid color:
- On the root shape element 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 a rectangle is being defined. See the Android documentation on shapes 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 documentation to see how a gradient is defined. To use the shape reference the drawable from a layout or view using the android:background attribute, in this case it would be used with android:background=»@drawable/customborder».
Add the Border to a Layout
This shape border is added, for a panel effect, to a layout, to which other views can be added as normal. Here the root RelativeLayout background is set to black (#000000, a hexadecimal alpha RGB value) and padding set to 10dp to help the border stand out. Drag and drop a LinearLayout onto the screen and set the border background (android:background=»@drawable/customborder»). In this example the existing single TextView is moved onto the LinearLayout. Tip: If required use the Component Tree to move Views and Widgets around. The TextView’s background is set to blue, plus some transparency to reduce the brightness (#A00000FF). The TextVew text is set white (#FFFFFF), enlarged (android:textSize=»40sp») and centered (android:gravity=»center_vertical|center_horizontal»). The layout code in activity_main.xml in the res/layout folder should be similar to this:
Play around with values and attributes to see what effect they have on the layout. Use the Android documentation to understand what the attributes do. Try adding other layouts and controls to experiment with different looks. Getting an App to look good adds to it’s appeal.
Download the code for this article ready for importing into Studio. The code can also be accessed via the Android Example Projects page. A version of this article appears in the Android Cookbook.
Archived Comments
2012/02/15 at 12:13 pm — Daniel — I found it very useful. Thanks.
But I have a little question. Can I have a white background and give a color only to the border of the button?
2012/02/15 at 8:15 pm — Tek Eye — In reply to Daniel.
Buttons need three drawables to be fully supported; for the normal, focus and pressed states. By default 9-patch files are used for button backgrounds. XML shape files can be used as well, to get what you require stack two shapes with different colors using a layer-list:
Save it in the drawables folder, use it like other drawables. To support button states you’ll need three different versions referenced from a selector drawable.
2012/08/13 at 2:22 pm — Erez — Thanks, very helpful and clear!
Author: Daniel S. Fowler Published: 2012-02-08 Updated: 2016-07-03
Do you have a question or comment about this article?
(Alternatively, use the email address at the bottom of the web page.)
↓markdown↓ CMS is fast and simple. Build websites quickly and publish easily. For beginner to expert.
Free Android Projects and Samples:
Источник
Как поместить границу вокруг Android textview?
можно ли нарисовать границу вокруг textview?
16 ответов
вы можете установить фигуру drawable (прямоугольник) в качестве фона для представления.
и прямоугольник drawable назад.xml (положить в папку res/drawable):
можно использовать @android:color/transparent для сплошного цвета, чтобы иметь прозрачный фон. Вы также можете использовать отступы, чтобы отделить текст от границы. для получения дополнительной информации см.: http://developer.android.com/guide/topics/resources/drawable-resource.html
позвольте мне суммировать несколько различных (не программных) методов.
использование фигуры drawable
сохраните следующее как XML-файл в папке drawable (например, my_border.XML-код):
затем просто установите его в качестве фона для вашего TextView:
использование 9-патч
9-патч-это растягивающееся фоновое изображение. Если вы создадите изображение с границей, оно даст вашему TextView границу. Все, что вам нужно сделать, это сделать изображение, а затем установить его в фоновом режиме в TextView.
вот некоторые ссылки, которые покажут, как сделать 9-патч изображение:
что, если я просто хочу верхнюю границу?
использование layer-list
вы можете использовать список слоев для укладки двух прямоугольников друг на друга. Сделав второй прямоугольник немного меньше первого, вы можете создать эффект границы. Этот первый (нижний) прямоугольник-это цвет границы, а второй прямоугольник-цвет фона.
задание android:top=»2dp» смещает верхнюю часть (делает ее меньше) на 2dp. Это позволяет показать первый (нижний) прямоугольник, давая эффект границы. Вы можете применить это к фону TextView так же, как shape drawable было сделано выше.
вот еще несколько ссылок о списках слоя:
использование 9-патч
вы можете просто сделать 9-патч изображение с одной границей. Все остальное — то же самое, что обсуждалось выше.
режим
это своего рода трюк, но он работает ну, если вам нужно добавить разделитель между двумя представлениями или границу в один TextView.
вот еще несколько ссылок:
простой способ-добавить представление для вашего TextView. Пример для нижней границы:
для других границ направления, пожалуйста отрегулируйте положение вида разделителя.
Я решил эту проблему, расширив textview и нарисовав границу вручную. Я даже добавил, чтобы вы могли выбрать, пунктирная или пунктирная граница.
и класс границы:
надеюсь, это поможет кому-то:)
Я просто смотрел на аналогичный ответ — Это можно сделать с помощью Штриха и следующего переопределения:
вы можете установить границу двумя методами. Один drawable и второй программ.
Использование Drawable
Я нашел лучший способ поместить границу вокруг TextView.
используйте изображение с девятью патчами для фона. Это довольно просто, SDK поставляется с инструментом для создания 9-патч-образа, и он включает в себя абсолютно нет кодировка.
папка drawable в res в проекте Android не ограничивается растровыми изображениями (PNG или JPG-файлами), но также может содержать фигуры, определенные в XML-файлах.
эти формы затем могут быть повторно использованы в проекте. Фигуру можно использовать для размещения границы вокруг макета. В этом примере показана прямоугольная граница с изогнутыми углами. Новый файл под названием customborder.XML создается в папке мешочки (в Eclipse меню Файл и выберите новый файл, с папку выигрышного выбран введите имя файла и нажмите кнопку Готово).
вводится XML, определяющий форму границы:
атрибут android:shape имеет значение прямоугольник (файлы формы также поддерживают овал, линию и кольцо). Rectangle-это значение по умолчанию, поэтому этот атрибут можно опустить, если он задан как прямоугольник. См. документацию по Android на фигурах в http://developer.android.com/guide/topics/resources/drawable-resource.html#Shape для получения подробной информации о файле формы.
углы элемента задает углы прямоугольника, которые должны быть закруглены. Можно задать разный радиус на каждом углу (см. ссылку на Android).
атрибуты заполнения используются для перемещения содержимого представления, к которому применяется форма, чтобы предотвратить перекрытие содержимого граница.
в цвет границы здесь установлен на светло-серый (CCCCCC шестнадцатеричное значение RGB).
формирует и поддерживает градиенты, но это не используется здесь. Опять же, см. ресурсы Android, чтобы увидеть, как определяется градиент. Форма применяется к laypout с помощью android:background=»@drawable/customborder» .
в макете другие виды могут быть добавлены как обычно. В этом примере было добавлено одно TextView, и текст белый (ffffff шестнадцатеричный RGB). Фон установлен на синий, плюс некоторая прозрачность для уменьшения яркости (a00000ff шестнадцатеричное значение альфа RGB). Наконец, макет смещается от края экрана, помещая его в другой макет с небольшим количеством отступов. Полный файл макета таким образом:
Источник
Android Border – Draw Android Textview Border
Hi and welcome to another tutorial from Codingdemos, in this tutorial you will learn how to draw Android border around a TextView.
By the end of this tutorial, you will have an app that looks like this. (Large preview)
In this tutorial we will be using the following:
- – Android studio version 3.0.1
– Android emulator Nexus 5X with API 26
– Minimum SDK API 16
1- Open up Android Studio and open any project that you have in your computer.
Create new Android Studio project or open existing project. (Large preview)
2- Next open up colors.xml file to change the main colors of the app.
3- Now you can build and run the app to see the new colors.
4- Create a new Drawable resource file under drawable folder and name it textview_border.
textview_border.xml file created under drawable folder. (Large preview)
5- Open up textview_border.xml file and add the following code.
This is the file that you will use it later to draw Android Textview border. Here you specify the shape you want to draw as Rectangle, then you specify the thickness of Android border and color by using Stroke.
Preview of Android Textview border. (Large preview)
6- Now open up activity_main.xml file and add Android TextView.
This Android TextView is positioned in the top-center of the screen with margin from the top (30dp), increased text size to (30sp) and set the label of the text to (codingdemos.com).
7- Next you can apply the rectangle shape on this TextView by referencing textview_border.xml and using it as a background.
8- Now build and run the app to see the result.
9- You can see from the output above that the text is very close to the sides of the rectangle shape, you can fix that by adding some padding around Android TextView.
10- Now build and run the app to see the progress.
Android border around TextView. (Large preview)
11- I hope you find this tutorial helpful and if you have any question please post them in the comment below.
Источник