如何将边框添加到视图的特定一侧

How to add a border to a particular side of a view

这就是我为 EditText 添加边框的方法。我怎样才能只在 EditText 的一侧添加边框,并定义边框的颜色和宽度?

EditText editText = new EditText(this);
editText.setText("Find");
editText.setWidth(555);

GradientDrawable border = new GradientDrawable();
border.setColor(0xFFFFFFFF);  // white background
border.setStroke(1, 0xFF000000);  // black border with full
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN) {
    editText.setBackgroundDrawable(border);
} else {
    editText.setBackground(border);
}

Vielen dank im voraus.

如果您只想在 EditText 的一侧添加边框,那么您应该在布局文件中使用 View 标签绘制一条简单的线并将其放在 EditText 附近,并使用背景 属性 设置线的颜色. 要绘制水平线,请使用:

 <View
    android:layout_width="match_parent"
    android:background="@color/colorPrimary"
    android:layout_height="2dp" />

要在一侧获得边框,您可以像这样创建自己的可绘制对象:

<?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="#FF0000" />
    </shape>
  </item>
  <item android:right="5dp">
    <shape android:shape="rectangle">
      <solid android:color="#FFFF" />
    </shape>
  </item>
</layer-list>

并将此可绘制对象设置为您的 EditText 的背景。