使FrameLayout扩展,它也是孩子

时间:2011-10-17 13:13:05

标签: android android-layout android-view

如何动态更改FrameLayout的大小,并且它的子节点也会被扩展?

编辑:到目前为止,我得到了这个但是不起作用:

public class ResizableArea extends FrameLayout {
    private View child;

    public ResizableArea(Context context) {
        super(context);
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        if (event.getPointerCount() > 1){
            Vector2D p1 = new Vector2D(event.getX(0), event.getY(0));
            Vector2D p2 = new Vector2D(event.getX(1), event.getY(1));

            float dist = p1.minus(p2).getSize();

            resizeChildBy(dist);
        }
        return true;
    }

    private void resizeChildBy(float size) {
        LayoutParams params = (LayoutParams) child.getLayoutParams();
        params.height -= size;
        params.width -= size;
        child.setLayoutParams(params);
        invalidate();
    }


    @Override
    public void addView(View child) {
        if (getChildCount() != 0)
            throw new IllegalStateException("ResizableArea can only have one child attached!");

        this.child = child;
        super.addView(child);
    }

}

1 个答案:

答案 0 :(得分:0)

实际上,这是正确答案:

public class ResizableArea extends FrameLayout {
    private View child;

    public ResizableArea(Context context) {
        super(context);
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        if (event.getPointerCount() > 1){
            Vector2D p1 = new Vector2D(event.getX(0), event.getY(0));
            Vector2D p2 = new Vector2D(event.getX(1), event.getY(1));

            float dist = p1.minus(p2).getSize();

            if (lastDist == 0) {
                lastDist = dist;
                return true;
            }

            resizeChildsBy(lastDist - dist);
            lastDist = dist;
        }
        return true;
    }

    private void resizeChildBy(float size) {
        LayoutParams params = (LayoutParams) child.getLayoutParams();
        params.height -= size;
        params.width -= size;
        child.setLayoutParams(params);
        invalidate();
    }


    @Override
    public void addView(View child) {
        if (getChildCount() != 0)
            throw new IllegalStateException("ResizableArea can only have one child attached!");

        this.child = child;
        super.addView(child);
    }

}