¿Cómo pongo un borde alrededor de un textview de Android?


¿Es posible dibujar un borde alrededor de textview?

Author: Peter Mortensen, 2010-08-16

16 answers

Puede establecer un elemento de diseño de forma (un rectángulo) como fondo para la vista.

<TextView android:text="Some text" android:background="@drawable/back"/>

Y rectángulo dibujable de nuevo.xml (poner en la carpeta res/drawable):

<shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="rectangle" >
   <solid android:color="@android:color/white" />
   <stroke android:width="1dip" android:color="#4fa5d5"/>
</shape>

Puede usar @android:color/transparent para que el color sólido tenga un fondo transparente. También puede usar relleno para separar el texto del borde. para más información ver: http://developer.android.com/guide/topics/resources/drawable-resource.html

 1106
Author: Konstantin Burov,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-04-03 04:53:11

Permítanme resumir algunos métodos diferentes (no programáticos).

Usando un elemento de diseño de forma

Guarde lo siguiente como un archivo XML en su carpeta de elementos de diseño (por ejemplo, my_border.xml):

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="rectangle" >

    <!-- View background color -->
    <solid
        android:color="@color/background_color" >
    </solid>

    <!-- View border color and width -->
    <stroke
        android:width="1dp"
        android:color="@color/border_color" >
    </stroke>

    <!-- The radius makes the corners rounded -->
    <corners
        android:radius="2dp"   >
    </corners>

</shape>

Luego simplemente establézcalo como el fondo de su TextView:

<TextView
    android:id="@+id/textview1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:background="@drawable/my_border" />

Más ayuda:

Usando un parche 9

A 9-patch es una imagen de fondo estirable. Si haces una imagen con un borde, entonces le dará a tu TextView un borde. Todo lo que necesita hacer es crear la imagen y luego establecerla en el fondo en su TextView.

<TextView
    android:id="@+id/textview1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:background="@drawable/my_ninepatch_image" />

Aquí hay algunos enlaces que mostrarán cómo hacer una imagen de 9 parches:

¿Qué pasa si solo quiero el borde superior?

Usando una layer-list

Puede usar una lista de capas para apilar dos rectángulos uno encima del otro. Al hacer que el segundo rectángulo sea un poco más pequeño que el primer rectángulo, puede hacer un efecto de borde. El primer rectángulo (inferior) es el color del borde y el segundo rectángulo es el color de fondo.

<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">

    <!-- Lower rectangle (border color) -->
    <item>
        <shape android:shape="rectangle">
            <solid android:color="@color/border_color" />
        </shape>
    </item>

    <!-- Upper rectangle (background color) -->
    <item android:top="2dp">
        <shape android:shape="rectangle">
            <solid android:color="@color/background_color" />
        </shape>
    </item>
</layer-list>

Establecer android:top="2dp" compensa la parte superior (la hace más pequeña) por 2dp. Esto permite el primer rectángulo (inferior) para mostrar a través, dando un efecto de borde. Puede aplicar esto al fondo de TextView de la misma manera que el elemento de diseño shape se hizo anteriormente.

Aquí hay algunos enlaces más sobre las listas de capas:

Usando un 9-parche

Solo puede hacer una imagen de 9 parches con un solo borde. Todo lo demás es el mismo que se discutió anteriormente.

Usando una vista

Esto es una especie de truco, pero funciona bien si necesita agregar un separador entre dos vistas o un borde a una sola vista de texto.

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

    <TextView
        android:id="@+id/textview1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />

    <!-- This adds a border between the TextViews -->
    <View
        android:layout_width="match_parent"
        android:layout_height="2dp"
        android:background="@android:color/black" />

    <TextView
        android:id="@+id/textview2"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />

</LinearLayout>

Aquí hay algunos enlaces más:

 144
Author: Suragch,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-05-23 12:18:26

La forma sencilla es agregar una vista para su TextView. Ejemplo para la línea de borde inferior:

<LinearLayout android:orientation="vertical"
              android:layout_width="fill_parent"
              android:layout_height="fill_parent">
    <TextView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="10dp"
        android:layout_marginLeft="10dp"
        android:text="@string/title"
        android:id="@+id/title_label"
        android:gravity="center_vertical"/>
    <View
        android:layout_width="fill_parent"
        android:layout_height="0.2dp"
        android:id="@+id/separator"
        android:visibility="visible"
        android:background="@android:color/darker_gray"/>

</LinearLayout>

Para los otros bordes de dirección, ajuste la ubicación de la vista separador.

 46
Author: Young Gu,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-01-02 00:38:34

He resuelto este problema extendiendo textview y dibujando un borde manualmente. Incluso agregué para que pueda seleccionar si un borde está punteado o discontinuado.

public class BorderedTextView extends TextView {
        private Paint paint = new Paint();
        public static final int BORDER_TOP = 0x00000001;
        public static final int BORDER_RIGHT = 0x00000002;
        public static final int BORDER_BOTTOM = 0x00000004;
        public static final int BORDER_LEFT = 0x00000008;

        private Border[] borders;

        public BorderedTextView(Context context, AttributeSet attrs, int defStyle) {
            super(context, attrs, defStyle);
            init();
        }

        public BorderedTextView(Context context, AttributeSet attrs) {
            super(context, attrs);
            init();
        }

        public BorderedTextView(Context context) {
            super(context);
            init();
        }
        private void init(){
            paint.setStyle(Paint.Style.STROKE);
            paint.setColor(Color.BLACK);
            paint.setStrokeWidth(4);        
        }
        @Override
        protected void onDraw(Canvas canvas) {
            super.onDraw(canvas);
            if(borders == null) return;

            for(Border border : borders){
                paint.setColor(border.getColor());
                paint.setStrokeWidth(border.getWidth());

                if(border.getStyle() == BORDER_TOP){
                    canvas.drawLine(0, 0, getWidth(), 0, paint);                
                } else
                if(border.getStyle() == BORDER_RIGHT){
                    canvas.drawLine(getWidth(), 0, getWidth(), getHeight(), paint);
                } else
                if(border.getStyle() == BORDER_BOTTOM){
                    canvas.drawLine(0, getHeight(), getWidth(), getHeight(), paint);
                } else
                if(border.getStyle() == BORDER_LEFT){
                    canvas.drawLine(0, 0, 0, getHeight(), paint);
                }
            }
        }

        public Border[] getBorders() {
            return borders;
        }

        public void setBorders(Border[] borders) {
            this.borders = borders;
        }
}

Y la clase border:

public class Border {
    private int orientation;
    private int width;
    private int color = Color.BLACK;
    private int style;
    public int getWidth() {
        return width;
    }
    public void setWidth(int width) {
        this.width = width;
    }
    public int getColor() {
        return color;
    }
    public void setColor(int color) {
        this.color = color;
    }
    public int getStyle() {
        return style;
    }
    public void setStyle(int style) {
        this.style = style;
    }
    public int getOrientation() {
        return orientation;
    }
    public void setOrientation(int orientation) {
        this.orientation = orientation;
    }
    public Border(int Style) {
        this.style = Style;
    }
}

Espero que esto ayude a alguien:)

 30
Author: Bojan Jovanovic,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-07-17 20:25:09

Estaba mirando una respuesta similar's se puede hacer con un trazo y la siguiente anulación:

@Override
public void draw(Canvas canvas, MapView mapView, boolean shadow) {

Paint strokePaint = new Paint();
strokePaint.setARGB(255, 0, 0, 0);
strokePaint.setTextAlign(Paint.Align.CENTER);
strokePaint.setTextSize(16);
strokePaint.setTypeface(Typeface.DEFAULT_BOLD);
strokePaint.setStyle(Paint.Style.STROKE);
strokePaint.setStrokeWidth(2);

Paint textPaint = new Paint();
textPaint.setARGB(255, 255, 255, 255);
textPaint.setTextAlign(Paint.Align.CENTER);
textPaint.setTextSize(16);
textPaint.setTypeface(Typeface.DEFAULT_BOLD);

canvas.drawText("Some Text", 100, 100, strokePaint);
canvas.drawText("Some Text", 100, 100, textPaint);

super.draw(canvas, mapView, shadow); 
}
 13
Author: sdtechcomm,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2011-07-26 20:08:45

Puede establecer el borde por dos métodos. Uno es por drawable y el segundo es programático.

Usando el elemento de diseño

<shape>
    <solid android:color="@color/txt_white"/>
    <stroke android:width="1dip" android:color="@color/border_gray"/>
    <corners android:bottomLeftRadius="10dp"
             android:bottomRightRadius="0dp"
             android:topLeftRadius="10dp"
             android:topRightRadius="0dp"/>
    <padding android:bottom="0dip"
             android:left="0dip"
             android:right="0dip"
             android:top="0dip"/>
</shape>

Programático


public static GradientDrawable backgroundWithoutBorder(int color) {

    GradientDrawable gdDefault = new GradientDrawable();
    gdDefault.setColor(color);
    gdDefault.setCornerRadii(new float[] { radius, radius, 0, 0, 0, 0,
                                           radius, radius });
    return gdDefault;
}
 10
Author: Maulik Santoki,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-01-02 00:49:24

Encontré una mejor manera de poner un borde alrededor de un TextView.

Utilice una imagen de nueve parches para el fondo. Es bastante simple, el SDK viene con una herramienta para hacer la imagen de 9 parches, e implica absolutamente no codificación.

El enlace es http://developer.android.com/guide/topics/graphics/2d-graphics.html#nine-patch.

 9
Author: Nick,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-01-02 00:36:56

Compruebe el enlace de abajo para hacer esquinas redondeadas http://androidcookbook.com/Recipe.seam?recipeId=2318

La carpeta del elemento de diseño, en res, en un proyecto Android no está restringida a mapas de bits (archivos PNG o JPG), sino que también puede contener formas definidas en archivos XML.

Estas formas pueden ser reutilizadas en el proyecto. Una forma se puede utilizar para poner un borde alrededor de un diseño. Este ejemplo muestra un borde rectangular con esquinas curvas. Un nuevo archivo llamado customborder.se crea xml en la imagen de la carpeta (en Eclipse utilice el menú Archivo y seleccione Nuevo Archivo, con la imagen de la carpeta seleccionada en el nombre de archivo y haga clic en Finalizar).

Se introduce el XML que define la forma del borde:

<?xml version="1.0" encoding="UTF-8"?>
    <shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="rectangle">
    <corners android:radius="20dp"/>
    <padding android:left="10dp" android:right="10dp" android:top="10dp" android:bottom="10dp"/>
    <solid android:color="#CCCCCC"/>
</shape>

El atributo android:shape se establece en rectángulo (los archivos de forma también admiten oval, línea y anillo). Rectangle es el valor predeterminado, por lo que este atributo podría omitirse si se trata de un rectángulo que se está definiendo. Consulte la documentación de Android sobre formas en http://developer.android.com/guide/topics/resources/drawable-resource.html#Shape para obtener información detallada sobre un archivo de forma.

El elemento esquinas establece las esquinas del rectángulo a redondear. Es posible establecer un radio diferente en cada esquina (consulte la referencia de Android).

Los atributos de relleno se utilizan para mover el contenido de la vista a la que se aplica la forma, para evitar que el contenido se superponga frontera.

El color del borde aquí se establece en una luz gris (valor RGB hexadecimal CCCCCC).

Las formas también soportan degradados, pero eso no se usa aquí. Una vez más, consulta los recursos de Android para ver cómo se define un degradado. La forma se aplica a la disposición usando android:background="@drawable/customborder".

Dentro de la maquetación se pueden añadir otras vistas de forma normal. En este ejemplo, se ha agregado un solo TextView, y el texto es blanco (FFFFFF hexadecimal RGB). El fondo se establece en azul, además de cierta transparencia para reducir el brillo (alfa hexadecimal A00000FF Valor RGB). Finalmente, el diseño se desplaza desde el borde de la pantalla colocándolo en otro diseño con una pequeña cantidad de relleno. El archivo de diseño completo es así:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
              android:orientation="vertical"
              android:layout_width="fill_parent"
              android:layout_height="fill_parent"
              android:padding="5dp">
    <LinearLayout android:orientation="vertical"
                  android:layout_width="fill_parent"
                  android:layout_height="fill_parent"
                  android:background="@drawable/customborder">
        <TextView android:layout_width="fill_parent"
                android:layout_height="fill_parent"
                android:text="Text View"
                android:textSize="20dp"
                android:textColor="#FFFFFF"
                android:gravity="center_horizontal"
                android:background="#A00000FF" />
    </LinearLayout>
</LinearLayout>
 8
Author: Bahaa Hany,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-01-02 00:41:48

Puedes añadir algo como esto en tu código:

<shape xmlns:android="http://schemas.android.com/apk/res/android"
       android:shape="rectangle" >
    <solid android:color="#ffffff" />
    <stroke android:width="1dip" android:color="#4fa5d5"/>
</shape>
 8
Author: newbie,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-01-02 00:42:43

Tengo una manera de hacerlo muy simple, y me gustaría compartirla.

Cuando quiero cuadrar mis vistas de texto, simplemente las pongo en un LinearLayout. Establezco el color de fondo de mi LinearLayout, y agrego un relleno a mi TextView. El resultado es exactamente como si cuadrara TextView.

 5
Author: Roman Panaget,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-01-02 00:46:51

La solución más simple que he encontrado (y que realmente funciona):

<TextView
    ...
    android:background="@android:drawable/editbox_background" />
 3
Author: Protean,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-04-04 20:47:27

Aquí está mi clase auxiliar 'simple' que devuelve una ImageView con el borde. Simplemente coloque esto en su carpeta utils, y llámelo así:

ImageView selectionBorder = BorderDrawer.generateBorderImageView(context, borderWidth, borderHeight, thickness, Color.Blue);

Aquí está el código.

/**
 * Because creating a border is Rocket Science in Android.
 */
public class BorderDrawer
{
    public static ImageView generateBorderImageView(Context context, int borderWidth, int borderHeight, int borderThickness, int color)
    {
        ImageView mask = new ImageView(context);

        // Create the square to serve as the mask
        Bitmap squareMask = Bitmap.createBitmap(borderWidth - (borderThickness*2), borderHeight - (borderThickness*2), Bitmap.Config.ARGB_8888);
        Canvas canvas = new Canvas(squareMask);

        Paint paint = new Paint();
        paint.setStyle(Paint.Style.FILL);
        paint.setColor(color);
        canvas.drawRect(0.0f, 0.0f, (float)borderWidth, (float)borderHeight, paint);

        // Create the darkness bitmap
        Bitmap solidColor = Bitmap.createBitmap(borderWidth, borderHeight, Bitmap.Config.ARGB_8888);
        canvas = new Canvas(solidColor);

        paint.setStyle(Paint.Style.FILL);
        paint.setColor(color);
        canvas.drawRect(0.0f, 0.0f, borderWidth, borderHeight, paint);

        // Create the masked version of the darknessView
        Bitmap borderBitmap = Bitmap.createBitmap(borderWidth, borderHeight, Bitmap.Config.ARGB_8888);
        canvas = new Canvas(borderBitmap);

        Paint clearPaint = new Paint();
        clearPaint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.CLEAR));

        canvas.drawBitmap(solidColor, 0, 0, null);
        canvas.drawBitmap(squareMask, borderThickness, borderThickness, clearPaint);

        clearPaint.setXfermode(null);

        ImageView borderView = new ImageView(context);
        borderView.setImageBitmap(borderBitmap);

        return borderView;
    }
}
 1
Author: Aggressor,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-01-02 00:47:42

Esto puede ayudarte.

<RelativeLayout
    android:id="@+id/textbox"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_centerHorizontal="true"
    android:layout_centerVertical="true"
    android:background="@android:color/darker_gray" >

    <TextView
        android:id="@+id/text"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_centerVertical="true"
        android:layout_margin="3dp"
        android:background="@android:color/white"
        android:gravity="center"
        android:text="@string/app_name"
        android:textSize="20dp" />

</RelativeLayout
 0
Author: Mete,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-07-11 17:21:35

Cree una vista de borde con el color de fondo como el color del borde y el tamaño de su vista de texto. establecer el relleno de la vista de borde como el ancho del borde. Establezca el color de fondo de la vista de texto como el color que desee para la vista de texto. Ahora agregue su vista de texto dentro de la vista de borde.

 0
Author: praveen agrawal,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-01-10 09:25:29

Cambiando Konstantin Burov respuesta porque no funciona en mi caso:

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item>
        <shape android:shape="rectangle">
            <solid android:color="@android:color/white" />
            <stroke android:width="2dip" android:color="#4fa5d5"/>
            <corners android:radius="7dp"/>
        </shape>
    </item>
</selector>

CompileSdkVersion 26 (Android 8.0), minSdkVersion 21 (Android 5.0), targetSdkVersion 26, ejecución ' com.androide.soporte: appcompat-v7: 26.1.0', gradle: 4.1

 0
Author: Ed1085,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-05-15 22:05:52

En realidad, es muy simple. Si desea un rectángulo negro simple detrás de Textview, simplemente agregue android:background="@android:color/black" dentro de las etiquetas TextView. Así:

<TextView
    android:textSize="15pt" android:textColor="#ffa7ff04"
    android:layout_alignBottom="@+id/webView1"
    android:layout_alignParentRight="true"
    android:layout_alignParentEnd="true"
    android:background="@android:color/black"/>
 -1
Author: user3631822,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-01-02 00:43:28