自定义framelayout
时间: 2023-08-08 21:14:02 浏览: 57
FrameLayout 是 Android 中的布局容器之一,它允许我们将子视图重叠在一起。自定义 FrameLayout 可以通过继承 FrameLayout 类并在其中添加自己的功能来实现。
以下是一个自定义 FrameLayout 的示例代码:
```
public class CustomFrameLayout extends FrameLayout {
private Paint paint;
public CustomFrameLayout(Context context) {
super(context);
init();
}
public CustomFrameLayout(Context context, AttributeSet attrs) {
super(context, attrs);
init();
}
public CustomFrameLayout(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
init();
}
private void init() {
paint = new Paint();
paint.setColor(Color.RED);
paint.setStyle(Paint.Style.STROKE);
paint.setStrokeWidth(4);
}
@Override
protected void dispatchDraw(Canvas canvas) {
super.dispatchDraw(canvas);
canvas.drawRect(0, 0, getWidth(), getHeight(), paint); // 在 FrameLayout 上绘制矩形边框
}
}
```
这个自定义 FrameLayout 继承自 FrameLayout 类,并添加了一个绘制矩形边框的功能。在 `init()` 方法中初始化绘制属性,`dispatchDraw()` 方法在绘制子视图后绘制矩形边框。可以在布局文件中使用该自定义 FrameLayout,例如:
```
<com.example.myapplication.CustomFrameLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!" />
</com.example.myapplication.CustomFrameLayout>
```
这样就可以在 FrameLayout 上绘制一个红色矩形边框了。