我正在尝试创建一个新的自定义视图,而不是放一些重复的视图(稍后将通过java进行更改,如在自定义背景中等)
但是在3个视图中,我放入了线性布局,只有第一个被绘制。
尝试使用多个自定义视图,并且行为相同 - 只绘制第一个视图。
为什么?
代码段:
public class CustomView extends View {
public CustomView(Context context, AttributeSet attrs) {
super(context, attrs);
}
@Override
protected void onDraw(Canvas canvas) {
float top = getTop();
float bottom = getBottom();
float right = getRight();
float left = getLeft();
float width = right - left;
float height = bottom - top;
float rectSize = Math.min(width, height)/10;
float centerX = left + width/2;
float centerY = top + height/2;
Paint paint = new Paint();
paint.setStyle(Paint.Style.FILL);
paint.setColor(Color.RED);
canvas.drawRect(left, top, right,bottom, paint);
paint.setColor(Color.BLUE);
canvas.drawRect(centerX-rectSize, centerY-rectSize, centerX+rectSize, centerY+rectSize, paint);
}
}
的xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal"
>
<com.example.halamishre.myapplication.CustomView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="1"
/>
<com.example.halamishre.myapplication.CustomView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="1"
/>
<com.example.halamishre.myapplication.CustomView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="1"
/>
</LinearLayout>
答案 0 :(得分:0)
您的自定义视图有问题,因为您正在使用权重getRight()&amp; getLeft()方法为所有3提供相同的值,并且无法绘制剩余的两个视图。使用以下代码
float top = 0;
float bottom = getMeasuredHeight;
float right = getMeasuredWidth();
float left = 0;
float width = getMeasuredWidth();
float height = getMeasuredHeight();
float rectSize = Math.min(width, height)/10;
float centerX = width/2;
float centerY = height/2;
答案 1 :(得分:-1)
layout_weight
占据整个父母。您需要在案例中将weightSum
设置为3以显示权重1的所有3个自定义视图。或者您可以将每个权重设置为将添加到1的分数。