2011-08-17 70 views
4

我定義了一個視圖。該視圖包含一張圖片,用戶可以與之交互。我在我的主佈局中定義了一個FrameLayout,並且我在這個FrameLayout中以編程的方式添加了這個視圖。以編程方式在FrameLayout中的自定義視圖上設置邊距值

在視圖構造函數中,我定義了一個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

做child.layout(100,100,100 + child.getWidth(),100 + child.getHeight()); – Ronnie

+0

@ user7777777777沒有任何事情發生,我的觀點停留在左上角... – FinalSpirit

+0

我修改了我的答案。應該管用。 – Ronnie

回答

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);

+0

非常完美,非常感謝! – FinalSpirit

+0

是否必須重寫onMeasure方法? – Ronnie

+0

一個問題: 我在我的FrameLayout上覆蓋了onLayout(),然後迭代所有的孩子並調用view.layout(top,left,right,bottom);爲每個? – FinalSpirit

相關問題