2015-10-18 118 views
2

此代码添加了一个红色边框到的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?

回答

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); 
+0

什么做的伎俩是setLayerInset方法。 –