以编程方式将边框添加到LinearLayout

时间:2013-06-02 15:56:42

标签: android layout border

如何将以编程方式边框添加到LinearLayout? 让我们说我们创建这个布局:

LinearLayout TitleLayout = new LinearLayout(getApplicationContext());
TitleLayout.setOrientation(LinearLayout.HORIZONTAL);

那我该怎么办?

3 个答案:

答案 0 :(得分:42)

我认为上面的答案是不正确的:这个问题专门针对程序化版本要求,而你看到的第一件事是 xml 。 其次,部分xml在我的情况下几乎从来都不是一个选项,所以这是正确的答案:

    //use a GradientDrawable with only one color set, to make it a solid color
    GradientDrawable border = new GradientDrawable();
    border.setColor(0xFFFFFFFF); //white background
    border.setStroke(1, 0xFF000000); //black border with full opacity
    if(Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN) {
      TitleLayout.setBackgroundDrawable(border);
    } else {
      TitleLayout.setBackground(border);
    }

答案 1 :(得分:5)

在drawable文件夹中创建名为border.xml的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="#FF0000" /> 
    </shape>
  </item>   
    <item android:left="5dp" android:right="5dp"  android:top="5dp" >  
     <shape android:shape="rectangle"> 
      <solid android:color="#000000" />
    </shape>
   </item>    
 </layer-list> 

然后将此添加到线性布局作为背景:

android:background="@drawable/border"

<强>编程

TitleLayout.setBackgroundDrawable(getResources().getDrawable(R.drawable.border))

编辑:

自Jelly Bean以来,这个方法(setBackgroundDrawable已被弃用),所以你必须使用这个:

TitleLayout.setBackground(getResources().getDrawable(R.drawable.border));
希望这有帮助。

答案 2 :(得分:1)

对于Xamarin用户:

添加新的班级边框:

public class Border : Android.Graphics.Drawables.Drawable
{
    public Android.Graphics.Paint paint;
    public Android.Graphics.Rect bounds_rect;

    public Border(Android.Graphics.Color colour, int width)
    {
        this.paint = new Android.Graphics.Paint();
        this.paint.Color = colour;
        this.paint.StrokeWidth = width;
        this.paint.SetStyle(Android.Graphics.Paint.Style.Stroke);
    }

    public override int Opacity => 0;
    protected override void OnBoundsChange(Rect bounds)
    {
        base.OnBoundsChange(bounds);
        this.bounds_rect = bounds;
    }

    public override void Draw(Canvas canvas)
    {
        canvas.DrawRect(this.bounds_rect, this.paint);
    }

    public override void SetAlpha(int alpha)
    {
        //throw new NotImplementedException();
    }

    public override void SetColorFilter(ColorFilter colorFilter)
    {
        //throw new NotImplementedException();
    }
}

并像这样使用它:

TitleLayout.SetBackgroundDrawable(new Border(Color.Black, 5));