[英]Set programmatically margin values on a custom view in a FrameLayout
我定義了一個視圖。 該視圖包含一張圖片,用戶可以與之交互。 我在我的主布局中定義了一個 FrameLayout,並以編程方式在這個 FrameLayout 中添加了這個視圖。
在 View 構造函數中,我定義了一個 MarginLayutParams 以將此視圖放在屏幕的中心。 代碼是:
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 視圖從左上角沒有移動::(
你能幫助我嗎?
問候。
您應該重寫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);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.