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

Chr*_*tis 12 layout android border

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

LinearLayout TitleLayout = new LinearLayout(getApplicationContext());
TitleLayout.setOrientation(LinearLayout.HORIZONTAL);
Run Code Online (Sandbox Code Playgroud)

那我该怎么办?

小智 45

我相信上面的答案是不正确的:这个问题专门针对程序化版本来做,而你看到的第一件事就是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);
    }
Run Code Online (Sandbox Code Playgroud)


MDM*_*lik 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> 
Run Code Online (Sandbox Code Playgroud)

然后将此添加到线性布局作为背景,如下所示:

android:background="@drawable/border"
Run Code Online (Sandbox Code Playgroud)

编程

TitleLayout.setBackgroundDrawable(getResources().getDrawable(R.drawable.border))
Run Code Online (Sandbox Code Playgroud)

编辑:

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

TitleLayout.setBackground(getResources().getDrawable(R.drawable.border));
Run Code Online (Sandbox Code Playgroud)

希望这个帮助.