此代码为LinearLayout添加红色边框:
ShapeDrawable sd = new ShapeDrawable();
sd.setShape(new RectShape());
sd.getPaint().setColor(Color.RED);
sd.getPaint().setStrokeWidth(1f);
sd.getPaint().setStyle(Style.STROKE);
linearLayout.setBackground(sd);
我需要在布局的左侧添加一条红线。如何以编程方式执行此操作而不使用任何XML?
答案 0 :(得分:5)
这是一个解决方案:
GradientDrawable border = new GradientDrawable();
border.setStroke(1, color);
border.setGradientType(GradientDrawable.RECTANGLE);
Drawable[] layers = {border};
LayerDrawable layerDrawable = new LayerDrawable(layers);
layerDrawable.setLayerInset(0, 1, -2, -2, -2);
linearLayout.setBackground(layerDrawable);