我定义了一个视图。此视图包含图片,用户可以与之交互。我在主布局中定义了一个FrameLayout,并在此FrameLayout中以编程方式添加此视图。
在View构造函数中,我定义了一个MarginLayutParams,将此视图放在te屏幕的中心。代码是:
mLayoutParams = new MarginLayoutParams(picture.getWidth(), picture.getHeight);
mLayoutParams.setMargins(toCenterX, toCenterY, 0, 0);
setLayoutParams(mLayoutParams);
边距值不起作用...视图正确调整为宽度和高度定义,但视图不会按边距值缩放到视图中心...
编辑:
我的观点的模式:
-> View1 (i want sclae this view to the center)
Activity -> FrameLayout -> View2 (i want scale this view under the view 1)
-> View3 (i want scale this view at the top right)
这是我的ViewGroup示例。我实现了ViewGroup来管理所有视图:
public class MainView extends ViewGroup {
public BackgroundView mBackgroundWheelArea;
public BackgroundView mBackgroundLabelArea;
public WheelCoreView wheelCoreArea;
public LabelView labelArea;
public WheelOfFortuneActivity mActivity;
public MainView(Context pContext) {
super(pContext);
mActivity = (WheelOfFortuneActivity) pContext;
mBackgroundWheelArea = new BackgroundView(pContext, R.drawable.menu_background);
wheelCoreArea = new WheelCoreView(pContext, mActivity.fromPixelToDp(mBackgroundWheelArea
.getBackgroundHeight()), mActivity.fromPixelToDp(mBackgroundWheelArea
.getBackgroundWidth()));
labelArea = new LabelView(pContext, "Web");
mBackgroundLabelArea = new BackgroundView(pContext, R.drawable.menu_background_label);
this.addView(wheelCoreArea, 0);
}
@Override
protected void onLayout(boolean pChanged, int pL, int pT, int pR, int pB) {
final int count = getChildCount();
for (int i = 0; i < count; i++) {
View child = getChildAt(i);
child.layout(100, 100, 0, 0);
}
}
@Override
protected boolean drawChild(Canvas canvas, View child, long drawingTime) {
child.draw(canvas);
return true;
}
}
但是wheelCoreArea视图没有从左上角移动! :(
你能帮助我吗?
问候。
答案 0 :(得分:2)
您应该覆盖onLayout()
方法并手动设置视图边界,而不是设置边距。
调用view.layout(top, left, right, bottom);
维护成员变量的界限。
如果此视图的大小也发生变化,您可能还需要覆盖onMeasure
方法。
编辑: 尝试使用此公式计算视图放置点。
viewLeft = displayWidth()/2 - viewWidth/2;
viewTop = displayHeight()/2 - viewHeight/2;
致电view.layout(viewLeft , viewTop , viewLeft + viewWidth, viewTop + viewHeight);