gpt4 book ai didi

android - 在 FrameLayout 中的自定义 View 上以编程方式设置边距值

转载 作者:太空宇宙 更新时间:2023-11-03 10:30:09 31 4
gpt4 key购买 nike

我定义了一个 View 。此 View 包含一张图片,用户可以与之交互。我在主布局中定义了一个 FrameLayout,并以编程方式将此 View 添加到此 FrameLayout 中。

在 View 构造函数中,我定义了一个 MarginLayutParams 以将此 View 放在屏幕的中央。代码是:

mLayoutParams = new MarginLayoutParams(picture.getWidth(), picture.getHeight);
mLayoutParams.setMargins(toCenterX, toCenterY, 0, 0);
setLayoutParams(mLayoutParams);

边距值不起作用... View 已正确调整宽度和高度定义但 View 未按边距值缩放到 View 中心...

编辑:

我的观点:

                         -> 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 来管理所有 View :

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 View 没有从左上角移动! :(

你能帮帮我吗?

问候。

最佳答案

您应该覆盖 onLayout() 方法并手动设置 View 边界,而不是设置边距。

调用view.layout(top, left, right, bottom);维护成员变量的边界。

如果此 View 的大小也发生变化,您可能还需要重写 onMeasure 方法。

编辑

试试这个公式来计算 View 放置点。

viewLeft = displayWidth()/2 - viewWidth/2;
viewTop = displayHeight()/2 - viewHeight/2;

调用 view.layout(viewLeft , viewTop , viewLeft + viewWidth, viewTop + viewHeight);

关于android - 在 FrameLayout 中的自定义 View 上以编程方式设置边距值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7094040/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com