自定义 RelativeLayout 边框不显示
Custom RelativeLayout Border Not Showing
我创建一个自定义的RelativeLayout 来添加一个border.But 边框没有出现。
当我添加背景属性时,边框将 appear.When 我删除背景属性,边框 disappear.I 想要显示没有背景属性的边框。
谁能告诉我如何解决这个问题。
这是我的代码...
public class BorderRelativeLayout extends RelativeLayout {
Paint paint;
Rect rect;
public BorderRelativeLayout(Context context) {
super(context);
init();
}
public BorderRelativeLayout(Context context, AttributeSet attrs) {
super(context, attrs);
init();
}
public void init(){
paint = new Paint();
paint.setColor(Color.RED);
paint.setAntiAlias(true);
paint.setStyle(Paint.Style.STROKE);
paint.setStrokeWidth(20f);
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
rect = new Rect(0,0,getWidth(),getHeight());
canvas.drawRect(rect,paint);
}
}
对于 RelativeLayout
,除非您设置了背景,否则不会调用 onDraw()
。所以你不能用这种方式创建边框。
但是,与创建自定义子类相比,向 RelativeLayout
添加边框要容易得多。只需在 XML 中创建一个 ShapeDrawable
并将其分配给您的布局。
border.xml
<?xml version="1.0" encoding="utf-8"?>
<shape
xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle">
<stroke
android:width="5dp"
android:color="#f00"/>
</shape>
layout.xml
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="@drawable/border">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="24dp"
android:textColor="#000"
android:textStyle="bold"
android:text="hello world"/>
</RelativeLayout>
我创建一个自定义的RelativeLayout 来添加一个border.But 边框没有出现。 当我添加背景属性时,边框将 appear.When 我删除背景属性,边框 disappear.I 想要显示没有背景属性的边框。 谁能告诉我如何解决这个问题。
这是我的代码...
public class BorderRelativeLayout extends RelativeLayout {
Paint paint;
Rect rect;
public BorderRelativeLayout(Context context) {
super(context);
init();
}
public BorderRelativeLayout(Context context, AttributeSet attrs) {
super(context, attrs);
init();
}
public void init(){
paint = new Paint();
paint.setColor(Color.RED);
paint.setAntiAlias(true);
paint.setStyle(Paint.Style.STROKE);
paint.setStrokeWidth(20f);
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
rect = new Rect(0,0,getWidth(),getHeight());
canvas.drawRect(rect,paint);
}
}
对于 RelativeLayout
,除非您设置了背景,否则不会调用 onDraw()
。所以你不能用这种方式创建边框。
但是,与创建自定义子类相比,向 RelativeLayout
添加边框要容易得多。只需在 XML 中创建一个 ShapeDrawable
并将其分配给您的布局。
border.xml
<?xml version="1.0" encoding="utf-8"?>
<shape
xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle">
<stroke
android:width="5dp"
android:color="#f00"/>
</shape>
layout.xml
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="@drawable/border">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="24dp"
android:textColor="#000"
android:textStyle="bold"
android:text="hello world"/>
</RelativeLayout>