【问题标题】:How to put a border around an Android TextView?如何在 Android 文本视图周围放置边框?
【发布时间】:2011-03-30 14:29:40
【问题描述】:

是否可以在文本视图周围绘制边框?

【问题讨论】:

标签: android android-layout textview android-shapedrawable


【解决方案1】:

您可以将可绘制的形状(矩形)设置为视图的背景。

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

和矩形drawable back.xml(放入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>

您可以使用@android:color/transparent 使纯色具有透明背景。 您还可以使用填充将文本与边框分开。 欲了解更多信息,请参阅:http://developer.android.com/guide/topics/resources/drawable-resource.html

【讨论】:

  • 如果我只想要顶部边框怎么办?
  • @whyoz 他的方法为视图层次结构增加了不必要的复杂性。您将需要两个额外的视图(一个布局容器和边框视图)来使用他的方法。因此,如果您有许多需要添加边框的视图,您的视图树将变得难以管理。
  • @whyoz 但是这个方法可以通过样式和主题来应用,而永谷的方法不能用这种方式。
  • 对于仅顶部边框,请参阅this question
  • 你可以使用这个工具http://shapes.softartstudio.com来生成drawables。
【解决方案2】:

我只是在看一个类似的答案——它可以通过 Stroke 和以下覆盖来完成:

@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); 
}

【讨论】:

  • 太棒了!我唯一担心的是,当我在手机和模拟器中使用 drawRoundRect 时,边角的笔触很丑。
  • @erdomester 也许 Paint StrokePaint = new Paint(Paint.ANTI_ALIAS_FLAG);将解决“角落丑陋”的问题
【解决方案3】:

我找到了一种在 TextView 周围设置边框的更好方法。

使用九块图像作为背景。很简单,SDK 自带了制作 9-patch 图片的工具,而且绝对no编码。

链接是http://developer.android.com/guide/topics/graphics/2d-graphics.html#nine-patch

【讨论】:

  • 很有用,是的,但是这样更好吗?
  • 使用形状作为公认的答案比 9-patch 更好,XML 文件比图形资产更灵活
  • 形状方法没用。也许我是唯一一个经历过,标签“solid”总是被处理,无论是否设置为透明。如果我想创建一个边框,我的意思是,一个 BORDER 而不是一个带有彩色内部和其他彩色边界线的矩形。它永远不是透明的固体。它总是扰乱颜色。同样,从另一个继承的类也应该具有所有功能,因为它是继承的。真的无法理解,为什么基本的OO设计指南被android打破了。例如,我继承自按钮。所有功能都消失了。为什么?
  • @Jeremie 明显变慢了?你是怎么观察的?
  • “有限”和“程序化”不属于同一个句子。
【解决方案4】:

简单的方法是为您的 TextView 添加一个视图。下边框线示例:

<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>

对于其他方向的边框,请调整分隔视图的位置。

【讨论】:

  • 根据我的经验,这个解决方案在旧设备上对应用性能有明显的影响。
  • 从视图膨胀的角度来看,这是一个可怕的解决方案。您创建 3 个新视图元素并在视图层次结构深度中再添加一层
  • 最糟糕的解决方案,因为正如菲利普所说,观点膨胀的观点。您是否知道 textView 具有特定的 xml 标签来执行此操作:定义要在您的 TextView 周围绘制左/右/上/下的图片,它们被称为 android:drawable****
【解决方案5】:

我已经通过扩展 textview 并手动绘制边框解决了这个问题。 我什至添加了这样您就可以选择边框是虚线还是虚线。

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;
        }
}

还有边框类:

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;
    }
}

希望这可以帮助某人:)

【讨论】:

  • 如何初始化边框?
  • 它无法正常工作,因为代码显示它以定义值的一半大小绘制边框
【解决方案6】:

检查下面的链接以制作圆角 http://androidcookbook.com/Recipe.seam?recipeId=2318

Android 项目中 res 下的 drawable 文件夹不限于位图(PNG 或 JPG 文件),它还可以保存 XML 文件中定义的形状。

然后可以在项目中重复使用这些形状。形状可用于在布局周围放置边框。此示例显示了一个带有弯曲角的矩形边框。在 drawable 文件夹中创建了一个名为 customborder.xml 的新文件(在 Eclipse 中,使用 File 菜单并选择 New,然后选择 File,在文件名中选择 drawable 文件夹,然后单击 Finish)。

输入定义边框形状的 XML:

<?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>

属性android:shape 设置为矩形(形状文件也支持椭圆、直线和环形)。 Rectangle 是默认值,因此如果定义的是矩形,则可以省略此属性。有关形状文件的详细信息,请参阅http://developer.android.com/guide/topics/resources/drawable-resource.html#Shape 上有关形状的 Android 文档。

元素corners 将矩形角设置为圆角。可以在每个角上设置不同的半径(参见 Android 参考)。

padding 属性用于移动应用了形状的 View 的内容,以防止内容与 边框。

这里的边框颜色设置为浅灰色(CCCCCC十六进制RGB值)。

形状也支持渐变,但是这里没有用到。同样,请参阅 Android 资源以了解渐变是如何定义的。使用android:background="@drawable/customborder" 将形状应用于布局。

在布局中可以正常添加其他视图。在本例中,添加了单个 TextView,文本为白色(FFFFFF 十六进制 RGB)。背景设置为蓝色,加上一些透明度以降低亮度(A00000FF 十六进制 alpha RGB 值)。最后,通过将布局放置到具有少量填充的另一个布局中,布局从屏幕边缘偏移。完整的布局文件如下:

<?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>

【讨论】:

  • 非常不鼓励仅链接的答案,因为链接往往会在未来的某个时候断开。将链接的相关部分拉入此答案,以便信息仍然可用,即使链接不可用。
【解决方案7】:

您可以在代码中添加类似这样的内容:

<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>

【讨论】:

  • 为什么需要中风?
  • @IgorGanapolsky,中风创建实际边框?
【解决方案8】:

这可能会对你有所帮助。

<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

【讨论】:

    【解决方案9】:

    其实很简单。如果您想要 Textview 后面的简单黑色矩形,只需在 TextView 标记中添加android:background="@android:color/black"。像这样:

    <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"/>
    

    【讨论】:

    • 他要求边框不是完整的背景。
    【解决方案10】:

    让我总结一些不同的(非编程的)方法。

    使用可绘制的形状

    将以下内容保存为可绘制文件夹中的 XML 文件(例如,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>
    

    然后将其设置为 TextView 的背景:

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

    更多帮助:

    使用 9 补丁

    9-patch 是可拉伸的背景图像。如果您制作带有边框的图像,那么它将为您的 TextView 提供边框。您需要做的就是制作图像,然后将其设置为 TextView 中的背景。

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

    这里有一些链接将展示如何制作 9-patch 图像:

    如果我只想要顶部边框怎么办?

    使用层列表

    您可以使用图层列表将两个矩形堆叠在一起。通过使第二个矩形比第一个矩形小一点,您可以制作边框效果。第一个(下方)矩形是边框颜色,第二个矩形是背景色。

    <?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>
    

    设置android:top="2dp" 将顶部偏移(使其更小)2dp。这允许第一个(下部)矩形显示出来,产生边框效果。您可以将其应用于 TextView 背景,方法与上面的 shape 可绘制对象相同。

    这里有更多关于层列表的链接:

    使用 9 补丁

    您可以只制作带有单个边框的 9 补丁图像。其他一切都与上面讨论的相同。

    使用视图

    这是一种技巧,但如果您需要在两个视图之间添加分隔符或在单个 TextView 中添加边框,则效果很好。

    <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>
    

    这里有更多链接:

    【讨论】:

    • 天哪,border: 1px solid #999; 不应该是这个复杂的。
    • 如果我想要textview的边框,它也有阴影和涟漪效果?
    • @AkashDubey,对不起,我以前没有这样做过。我建议你分别尝试每一个,然后将它们组合起来。如果您遇到困难,请在 Stack Overflow 上提出一个新问题。
    【解决方案11】:

    我有一个非常简单的方法,我想分享一下。

    当我想平方 mi TextViews 时,我只是将它们放在一个 LinearLayout 中。我设置了我的 LinearLayout 的背景颜色,并为我的 TextView 添加了边距。结果与您将 TextView 平方完全一样。

    【讨论】:

      【解决方案12】:

      这是我的“简单”助手类,它返回一个带边框的 ImageView。只需将其放在您的 utils 文件夹中,然后像这样调用它:

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

      这里是代码。

      /**
       * 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;
          }
      }
      

      【讨论】:

      • 如何使用selectionBorder
      • @TashPemhiwa Button.setBackgroundDrawable();
      【解决方案13】:

      您可以通过两种方法设置边框。一个是可绘制的,第二个是程序化的。

      使用可绘制

      <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>
      

      程序化


      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;
      }
      

      【讨论】:

      • 该形状 XML 与 textView 有何关系?
      【解决方案14】:

      创建一个边框视图,其背景颜色作为边框颜色和文本视图的大小。将边框视图填充设置为边框的宽度。将文本视图背景颜色设置为文本视图所需的颜色。现在在边框视图中添加您的文本视图。

      【讨论】:

        【解决方案15】:

        我找到的最简单的解决方案(并且确实有效):

        <TextView
            ...
            android:background="@android:drawable/editbox_background" />
        

        【讨论】:

        • 是否可以将其应用于一个地方的所有文本视图?
        • 很适合速成。但根据运行设备的版本,这可能会产生非常不寻常的影响。这是因为谷歌一直在改变 EditTexts 的外观(你必须保持时尚!)
        【解决方案16】:

        更改 Konstantin Burov 的答案,因为在我的情况下不起作用:

        <?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, 实施 'com.android.support:appcompat-v7:26.1.0', 毕业:4.1

        【讨论】:

          【解决方案17】:

          试试这个:

          <shape>
              <solid android:color="@color/txt_white"/>
              <stroke android:width="1dip" android:color="@color/border_black"/>
          </shape>
          

          【讨论】:

            【解决方案18】:

            有很多方法可以给 textView 添加边框。最简单的方法是创建一个自定义可绘制对象并将其设置为 android:background="@drawable/textview_bg" 用于您的 textView。

            textview_bg.xml 将在 Drawables 下,可以是这样的。 您可以使用solidgradient 背景(如果不需要,则不需要),corners 添加圆角半径,stroke 添加边框。

            textview_bg.xml

            <?xml version="1.0" encoding="utf-8"?>
                <shape xmlns:android="http://schemas.android.com/apk/res/android"
                    android:shape="rectangle">
            
                    <corners
                        android:radius="@dimen/dp_10"/>
            
                    <gradient
                        android:angle="225"
                        android:endColor="#FFFFFF"
                        android:startColor="#E0E0E0" />
            
                    <stroke
                        android:width="2dp"
                        android:color="#000000"/>
            
                </shape>
            

            【讨论】:

              【解决方案19】:

              您可以为文本视图创建自定义背景。 步骤

              1. 转到您的项目。
              2. 转到资源并右键单击可绘制。
              3. 点击新建 -> 可绘制资源文件
              4. 为您的文件命名
              5. 在文件中粘贴以下代码
              <shape xmlns:android="http://schemas.android.com/apk/res/android">
                  <stroke
                      android:width="1dp"
                      android:color="@color/colorBlack" />
                  <padding
                      android:bottom="1dp"
                      android:left="1dp"
                      android:right="1dp"
                      android:top="1dp" />
                  <corners android:radius="6dp" />
                  <solid android:color="#ffffffff" />
              </shape>
              
              1. 对于您想要将其用作背景的文本视图,

                android:background="@drawable/your_fileName"

              【讨论】:

                【解决方案20】:
                  <View
                    android:layout_width="match_parent"
                    android:layout_height="2dp"
                    android:background="@android:color/black" />
                

                这段代码足够你可以放在任何你想要的地方

                【讨论】:

                  【解决方案21】:

                  在你的 xml 文本视图上设置背景,

                  将 rounded_textview.xml 文件添加到您的可绘制目录中。

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

                  在 textView 背景中设置可绘制文件。

                  【讨论】:

                    【解决方案22】:

                    借助材料组件库,您可以使用 MaterialShapeDrawable

                        <TextView
                            android:id="@+id/textview"
                            .../>
                    

                    然后您可以以编程方式应用MaterialShapeDrawable

                        TextView textView = findViewById(R.id.textview);
                        MaterialShapeDrawable shapeDrawable = new MaterialShapeDrawable();
                        shapeDrawable.setFillColor(ContextCompat.getColorStateList(this,android.R.color.transparent));
                        shapeDrawable.setStroke(1.0f, ContextCompat.getColor(this,R.color....));
                        ViewCompat.setBackground(textView,shapeDrawable);
                    

                    【讨论】:

                      【解决方案23】:

                      您可以将可绘制的形状(带角的矩形)设置为视图的背景。

                      <TextView android:background="@drawable/frame"/>
                      

                      和矩形drawable frame.xml(放入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="#3d4caf"/>
                          <corners android:radius="50dp"/>
                      </shape>
                      

                      【讨论】:

                        猜你喜欢
                        • 1970-01-01
                        • 1970-01-01
                        • 1970-01-01
                        • 2017-02-22
                        • 2015-06-19
                        • 1970-01-01
                        • 1970-01-01
                        • 1970-01-01
                        • 2013-02-04
                        相关资源
                        最近更新 更多