Android 如何设置控件边框只显示上面和下面(或者左边和右边)

本文介绍了一种使用XML实现自定义控件边框的方法。通过layer-list布局,可以灵活地为控件设置不同颜色及宽度的边框。具体实现中,通过两个item分别设置控件的背景色和底部边框。

效果图:

下面看如何实现:
控件:


实现功能的xml:

 
<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
    <item>
        <shape>//边框的颜色
            <!--<solid android:color="@color/gray" />-->
            <solid android:color="#ff9696" />
        </shape>
    </item>

    <item
        android:bottom="1dp"
        android:top="1dp">//这里有四个方向可以选择,这里因为只要显示底部边框,所以就设置bottom
        <shape>
            <solid android:color="@color/white" />
            //整个空间的背景颜色
        </shape>
    </item>

</layer-list>

参考链接:https://blog.youkuaiyun.com/binge__/article/details/54021067

Android中,要在TextView控件上添加可见的边框,你可以通过自定义View或者利用第三方库如`androidx.appcompat.widget.AppCompatTextView`结合XML布局以及代码来实现。以下是两种常见的方法: 1. **直接在XML布局中**: - 创建一个`<androidx.appcompat.widget.AppCompatTextView>`,然后使用`android:textAppearance`属性设置文本外观,同时在`<shape>`元素下定义边框样式: ```xml <com.google.android.material.textview.MaterialAutoCompleteTextView android:id="@+id/my_text_view" android:layout_width="wrap_content" android:layout_height="wrap_content" <!-- 添加边框 --> app:borderWidth="1dp" <!-- 边框宽度 --> app:cornerRadius="4dp" <!-- 角度,如果需要圆角 --> app:elevation="2dp" <!-- 深度感,增加立体效果 --> <!-- 设置边框颜色 --> app:borderColor="?attr/colorPrimary" /> ``` 2. **在代码中动态添加**: 如果你需要在程序运行时动态添加边框,可以在初始化TextView时使用`setLayerType()`方法: ```java AppCompatTextView textView = findViewById(R.id.my_text_view); textView.setLayerType(View.LAYER_TYPE_SOFTWARE, null); // 将视图层类型设为软件加速 textView.getBackground().setBorderPaint(new Paint()); // 获取背景画笔并设置边框样式 Paint borderPaint = new Paint(); borderPaint.setColor(Color.BLACK); // 设置边框颜色 borderPaint.setStyle(Paint.Style.STROKE); // 设定为实线边框 borderPaint.setStrokeWidth(2); // 设置边框宽度 textView.getBackground().drawBorder(borderPaint); // 绘制边框 ``` 记得替换上述示例中的颜色、宽度等参数,使之符合你的需求。
评论 1
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值