gpt4 book ai didi

android - 自定义 RelativeLayout 边框不显示

转载 作者:行者123 更新时间:2023-11-30 00:26:39 26 4
gpt4 key购买 nike

我创建了一个自定义的 RelativeLayout 来添加边框。但是边框没有出现。当我添加背景属性时,边框会出现。当我删除背景属性时,边框会消失。我想显示没有背景属性的边框。任何人都可以向我解释如何解决这个问题。

这是我的代码...

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 并将其分配给您的布局。

边框.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>

enter image description here

关于android - 自定义 RelativeLayout 边框不显示,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45240373/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com