Android自定义视图不能使用alignParentButton或wrap_content

时间:2012-08-04 11:04:48

标签: android custom-view

我有一个我不知道如何解决的问题。我创建了一个自定义视图,并希望在相对布局中将它与parrent buttom对齐,但是当我这样做时,视图变得透明了?!怎么会这样? 此外,如果我设置周围的视图layout_height = wrap_content它填充整个屏幕。如何配置它不要这样做但只包装内容?

这是我的自定义视图

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.LinearGradient;
import android.graphics.Paint;
import android.graphics.Rect;
import android.graphics.RectF;
import android.graphics.Shader;
import android.util.AttributeSet;
import android.view.View;
import android.view.ViewGroup.LayoutParams;
import android.widget.RelativeLayout;

public class HomeMenuBackground extends View
{ 
    private int mScreenWidth;
    private int mScreenHeight;
    private RectF mSpace;
    private RectF mSpaceStroke;
    private Paint mPaint;
    private Paint mPaintStroke;
    private Rect mRect; 
    private LinearGradient mGradient;

    public HomeMenuBackground(Context context, AttributeSet attrs)
    {
        super(context, attrs);

        mScreenWidth = context.getResources().getDisplayMetrics().widthPixels;
        mScreenHeight = context.getResources().getDisplayMetrics().heightPixels;
        final int mHeighMenu = (int) (mScreenHeight*0.8);
        mPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
        mSpace = new RectF(-20, 2, mScreenWidth + 20, 148);
        mSpaceStroke = new RectF(-22, 0, mScreenWidth + 22, 150);
        mRect = new Rect();

        mPaintStroke = new Paint();
        mPaintStroke.setStyle(Paint.Style.STROKE);
        mPaintStroke.setStrokeCap(Paint.Cap.ROUND);
        mPaintStroke.setStrokeWidth(2);
        mPaintStroke.setColor(Color.BLACK);
        mPaintStroke = new Paint(Paint.ANTI_ALIAS_FLAG);

    }

    @Override
    public void onDraw(Canvas canvas)
    {       
        mRect.set(0, 75, canvas.getWidth(), canvas.getHeight());
        canvas.drawArc(mSpaceStroke, 180, 360, true, mPaintStroke);
        canvas.drawArc(mSpace, 180, 360, true, mPaint);
        canvas.drawRect(mRect, mPaint);
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) 
    {
        if(mGradient == null)
        {
            mGradient = new LinearGradient(0, 0, 0, MeasureSpec.getSize(heightMeasureSpec), Color.WHITE, Color.GRAY, Shader.TileMode.MIRROR);
            mPaint.setShader(mGradient);
        }

        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
    }
}

我希望你能帮助我:D

BR FireFly3000

1 个答案:

答案 0 :(得分:2)

要确定自定义视图的高度和宽度,您可以覆盖setMeasuredDimension (int measuredWidth, int measuredHeight)方法,并根据您的要求提供视图的高度和宽度。我尝试使用RelativeLayout,我可以在setMeasuredDimension(100, 100);方法内使用onMeasure()看到底部的布局,高度和宽度为(100,100)。