怎么再linerlayout中绘制两个圆
时间: 2023-11-27 15:54:05 浏览: 27
您可以使用 `LinearLayout` 和 `View` 来实现绘制两个圆。可以通过继承 `View` 类来创建自定义视图,并在 `onDraw` 方法中绘制圆形。以下是一个示例代码:
1. 创建一个自定义视图类 `CircleView`:
```java
public class CircleView extends View {
private Paint paint;
private int color;
public CircleView(Context context, int color) {
super(context);
this.color = color;
paint = new Paint();
paint.setColor(color);
paint.setStyle(Paint.Style.FILL);
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
int width = getWidth();
int height = getHeight();
int radius = Math.min(width, height) / 2;
canvas.drawCircle(width / 2, height / 2, radius, paint);
}
}
```
2. 在布局文件中添加 `LinearLayout` 和 `CircleView`:
```xml
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<com.example.CircleView
android:layout_width="0dp"
android:layout_height="100dp"
android:layout_weight="1"
android:background="@android:color/transparent"
app:color="@color/red" />
<com.example.CircleView
android:layout_width="0dp"
android:layout_height="100dp"
android:layout_weight="1"
android:background="@android:color/transparent"
app:color="@color/blue" />
</LinearLayout>
```
3. 在 `CircleView` 类中添加一个 `color` 属性,并在布局文件中使用自定义属性来设置颜色:
```xml
<declare-styleable name="CircleView">
<attr name="color" format="color" />
</declare-styleable>
```
现在您可以在 `CircleView` 类中设置默认值,并在布局文件中使用自定义属性来设置颜色。通过更改 `LinearLayout` 的 `orientation` 属性,您可以更改两个圆的水平或垂直排列方式。