2011-08-17 154 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

相关问题