Search code examples
androidlayoutviewviewgroup

Set the child view at the TopLeft and BottomRight in a viewgroup


In my application I have the layout like this:

1) The main view can be moved and dragged.

2) Some controllers can be added to inside the main view. And their position can be set to TopLeft or something else. The TopLeft here means relative to the main view.(See this image)

Now I tried to implement this by extending the ViewGroup, and the main View and the controllers are all extends from View.

This is what I have done now:

class MyViewContainer extends ViewGroups{
   @Override
   public void onLayout(boolean changed,int l,int t,int b, int r){

      for(int i=0,len=getChildCounts,i<len;i++){
        View v=getChildAt(i);
        if(v instanceof MainView){
           v.layout(l,t,b,r);
        }
        else if(v instanceof MyController){
          //here do not now know how to layout the childs according to their position
        }
      }
   }
}
abstract MyController extends View{
}
class ZoomController extends MyController{
    @Override
    public void onDraw(Canvas c){

    }
}
class AnotherController extends MyController{
    @Override
    public void onDraw(Canvas c){

    }
}
class MainView extends View{
    @Override
    public void onDraw(Canvas c){

    }
}

As you can see, I have no idea to layout the MyControllers. Since I do not exactly know the width and height of the controller. Beacuse the size of controllers is depended on how it is being drawn.

How to make it?


Solution

  • Try this. For this to work, the master view has to come before the controllers.

    class MyViewContainer extends ViewGroups{
        @Override
        public void onLayout(boolean changed,int l,int t,int b, int r){
            View masterView = null;
            for(int i=0,len=getChildCounts,i<len;i++){
                View v=getChildAt(i);
                if(v instanceof MainView){
                    masterView = v;
                    v.layout(l,t,b,r);
                }
                else if(v instanceof MyController){
                    // Layout your views here.
                    RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
                    if (masterView != null && topLeft) {
                        params.addRule(RelativeLayout.ALIGN_LEFT, masterView.getId());
                        params.addRule(RelativeLayout.ALIGN_TOP, masterView.getId());
                    }
                    if (masterView != null && bottomRight) {
                        params.addRule(RelativeLayout.ALIGN_RIGHT, masterView.getId());
                        params.addRule(RelativeLayout.ALIGN_BOTTOM, masterView.getId());
                    }
                    v.setLayoutParams(params);
                }
            }
        }
    }