0
我无法正确布局自定义视图。
该视图非常简单,但覆盖onMeasure
始终为正方形,即高度和宽度应始终相同。自定义视图混淆了周围视图的布局
我的问题是,任何周围的视图变得困惑,并没有适当的大小自己。
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal"
android:layout_height="match_parent"
android:layout_width="match_parent">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<EditText
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1" />
<example.Square
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:color="@color/black" />
</LinearLayout>
</LinearLayout>
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal"
android:layout_height="match_parent"
android:layout_width="match_parent">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<EditText
android:id="[email protected]/edittext1"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<example.Square
android:layout_toRightOf="@id/edittext1"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:color="@color/black" />
</RelativeLayout>
</LinearLayout>
下面是自定义视图代码:
public class Square extends View {
private Paint paint;
protected void init() {
paint = new Paint(Paint.ANTI_ALIAS_FLAG);
paint.setStyle(Paint.Style.FILL);
paint.setColor(getResources().getColor(android.R.color.black));
}
public Square(Context context) {
super(context);
init();
}
public Square(Context context, AttributeSet attributeSet) {
super(context,attributeSet);
init();
}
public int getColor() {
return paint.getColor();
}
public void setColor(int color) {
paint.setColor(color);
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
int l = Math.min(getMeasuredHeight(),getMeasuredWidth());
setMeasuredDimension(l,l);
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
if ((getWidth() > 0) && (getHeight() > 0)) {
RectF r = new RectF(getPaddingLeft(), getPaddingTop(), getWidth()-getPaddingRight(), getHeight()-getPaddingBottom());
canvas.drawRect(r, paint);
}
}
}
你尝试'Log.d''int l'的值吗? – pskink