为android编写自定义LinearLayout

1 android android-layout

我有一个自定义布局,在其子项下面绘制一个透明的圆角矩形.问题是当我尝试将其添加到我的xml文件时,它不会显示.此外,当我尝试向其添加参数时(即android:layout_width)弹出窗口显示它们都不可用.我添加的任何子视图都会发生同样的事情.有人可以帮忙吗?

public class RoundRectLayout extends LinearLayout 
{ 
 private RectF shape;
 public RoundRectLayout(Context context)
 {
  super(context);
  LayoutInflater layoutInflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
  layoutInflater.inflate(R.layout.settings, this);
  shape = new RectF();
 }

 public RoundRectLayout(Context context, AttributeSet attrs)
 {
  super(context, attrs);
  LayoutInflater layoutInflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
  layoutInflater.inflate(R.layout.settings, this);
  shape = new RectF();
 }

 @Override
 protected void onSizeChanged(int w, int h, int oldw, int oldh)
 {
  shape = new RectF(0, 0, w - 5, h - 5);
  super.onSizeChanged(w, h, oldw, oldh);
 }

 @Override
 protected void dispatchDraw(Canvas canvas)
 {
  Paint temp = new Paint();
  temp.setAlpha(125);
  canvas.drawRoundRect(shape, 10f, 10f, temp);
  super.dispatchDraw(canvas);
 }
}
Run Code Online (Sandbox Code Playgroud)

小智 8

如果您只想要LinearLayout的圆角矩形背景,可以在"res/drawable /"中的xml文件中定义可绘制的形状:

<?xml version="1.0" encoding="UTF-8"?> 
<shape xmlns:android="http://schemas.android.com/apk/res/android"> 
    <solid android:color="#50000000"/>    
    <stroke android:width="3dp"
            android:color="#ffffffff"/>
    <padding android:left="5dp"
             android:top="5dp"
             android:right="5dp"
             android:bottom="5dp"/> 
    <corners android:bottomRightRadius="7dp"
             android:bottomLeftRadius="7dp" 
             android:topLeftRadius="7dp"
             android:topRightRadius="7dp"/> 
</shape>
Run Code Online (Sandbox Code Playgroud)

然后,设置布局的背景,你绘制的XML文件的名称.如果将其命名为round_border.xml,请将背景设置为:

<LinearLayout
   android:background="@drawable/round_border"
   ...
Run Code Online (Sandbox Code Playgroud)

透明度设置如下......

<solid android:color="#50000000"/>    
Run Code Online (Sandbox Code Playgroud)

前2位表示透明度,后6位是颜色.