如何在android中以编程方式在edittext上添加边框

时间:2014-11-11 17:30:00

标签: android xml

我正在开发演示应用程序,我需要以编程方式设置边框宽度和边框颜色。

我知道可以使用xml drawable完成,但我想在运行时完成所有这些操作。我知道通过创建xml并使用它来获得它们是好的,但我的要求是如此动态,所以我必须在运行时而不是在接近方法中完成所有这些工作。

border_edittext.xml

<shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="rectangle" >
    <solid android:color="#ffffff" />
    <stroke android:width="1dip" android:color="#000000"/>
</shape>

设置drawable。

EditText foo = (EditText)findViewById(R.id.editText);
foo.setBackgroundResource(R.drawable.border_edittext);

提前致谢。

1 个答案:

答案 0 :(得分:1)

Shape Drawables首先浮现在脑海中。 Android Guide有一些很好的细节。

    int x = 10;
    int y = 10;
    int width = 300;
    int height = 50;

    mDrawable = new ShapeDrawable(new RectShape()); // rectangle for border
    mDrawable.getPaint().setColor(0xff74AC23); // set color
    mDrawable.setBounds(x, y, x + width, y + height);   

    setContentView(mDrawable);

但那不是空心矩形,因为你可能想要边框。有关使用边框的更多讨论,请参阅this answer。棘手的部分是获得透明度。看起来有些人已经决定在画布的边框周围绘制四条线。

可以像这样创建画布。

Bitmap b = Bitmap.createBitmap(100, 100, Bitmap.Config.ARGB_8888);
Canvas c = new Canvas(b);