以编程方式在视图上添加/删除边框

问题描述

Android 中没有一种像 iOS 中那样以编程方式设置 View/ViewGroup/RelativeLayout 的边框的简单方法吗?

我在 Xamarin.Android 中使用 C#。在iOS中,就像

一样简单

View.Layer.BorderColor = X; View.Layer.BorderWidth = 2;

但是在搜索了许多站点和 Xamarin 文档之后,在 Android 中似乎没有一种简单的方法可以做到这一点。对我来说,上面很简单(一两行),但知道 Android 想要把一切都复杂化,我什至会满足于需要八九行代码解决方案。

是的,我确实需要一个程序化的解决方案,而不是编辑 XML。

我发现的许多类似问题的答案都没有提供以编程方式完成的方法

我找到的最接近的是这个 Android add border to edit text programmatically。但我想知道有没有更简单的方法来做看起来很常用的事情,而不是创建一个完整的类只是为了从视图中添加/删除边框? Android 真的忽略了这样一个看似有用且常见的属性吗?还是我完全被误导了,对这么简单的事情完全视而不见?

解决方法

在 drawable 中创建 2 个图层列表。

  1. box_with_border.xml:
<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
    <item>
        <shape android:shape="rectangle">
            <solid android:color="#fff" />
        </shape>
    </item>

    <item>
        <shape>
            <stroke
                android:width="2dp"
                android:color="#000" />
        </shape>
    </item>
</layer-list>
  1. box_without_border.xml:
<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
    <item>
        <shape android:shape="rectangle">
            <solid android:color="#fff" />
        </shape>
    </item>
</layer-list>

现在您可以为视图设置背景:

if (youWant) {
     your_layout.setBackground(ContextCompat.getDrawable(getContext(),R.drawable.box_with_border));
} else {
     your_layout.setBackground(ContextCompat.getDrawable(getContext(),R.drawable.box_without_border));
}