0

Is there not a simple way to programmatically set the border of a View / ViewGroup / RelativeLayout in Android like there is in iOS?

I'm working in C# in Xamarin.Android. In iOS, it's as simple as

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

But after scouring a number of sites and the Xamarin documentation, there doesn't seem to be a simple way to do this in Android. To me, simple is the above (one or two lines), but knowing Android's desire to over complicate everything, I would even settle for a solution that requires eight or nine lines of code.

Yes, I do require a programmatic solution, not editing the XML.

Many answers to similar questions I've found don't give a way to do it programmatically.

The closest I've found is this Android add border to edit text programmatically. But I'm wondering is there not a simpler way to do what seems like it would be a commonly used thing, rather than creating an entire class just to add/remove a border from a view? Did Android really overlook such a seemingly useful and common property? Or am I completely misguided and completely blind to something so simple?

Cfun
  • 8,442
  • 4
  • 30
  • 62
  • Android doesn't seem to be able to set a border to a control by setting a property, but you can create a new XML file under the Drawable and then set a background to the control to achieve this,like the solution in your link above. – Leo Zhu Jan 29 '21 at 02:54

1 Answers1

0

Create 2 layer-list in drawable.

  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>

And now you can set background to your view:

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));
}
Dilshod
  • 147
  • 4
  • 12