Search code examples
androidshapesviewgroup

Getting a reference to the parent ViewGroup


I am creating a scalable shape by adding a shape and handles as separate views to a ViewGroup. Once a handler is clicked, how do I get a reference to the ViewGroup so that I can scale everything? handle.getParent() returns null. My ViewGroup was created programmatically.

public class ShapeView extends ViewGroup {

    private SelectorView mSelectorView;

     public ShapeView (Context context) {
          super(context);
          RelativeLayout.LayoutParams p = new RelativeLayout.LayoutParams(200, 200);
          this.setLayoutParams(p);
          mSelectorView = new SelectorView(context);
          this.addView(mSelectorView);
    }
}


public class SelectorView extends View {

public RectangleDrawable mRectangleDrawable;

    public SelectorView (Context context) {
          super(context);
          Log.v(TAG, "constructor");
          mRectangleDrawable = new RectangleDrawable();
          RelativeLayout.LayoutParams p = new RelativeLayout.LayoutParams(20, 20);
          this.setLayoutParams(p);
    }

    @Override
    protected void onDraw(Canvas canvas) {  
          super.onDraw(canvas);
          mRectangleDrawable.draw(canvas); 
    }


    public boolean onTouchEvent(MotionEvent event) {

          switch (event.getAction()) {
             case MotionEvent.ACTION_DOWN: {
               ViewGroup parentView = (ViewGroup)this.getParent();
               parentView.setX(100);
               parentView.setY(100);
               break;
              }
           }
           return true; 
    }

}

Solution

  • Please use SelectorView.this.getParent() instead of this.getParent()

    public class SelectorView extends View {
    
    public RectangleDrawable mRectangleDrawable;
    
    public SelectorView (Context context) {
          super(context);
          Log.v(TAG, "constructor");
          mRectangleDrawable = new RectangleDrawable();
          RelativeLayout.LayoutParams p = new RelativeLayout.LayoutParams(20, 20);
          this.setLayoutParams(p);
    }
    
    @Override
    protected void onDraw(Canvas canvas) {  
          super.onDraw(canvas);
          mRectangleDrawable.draw(canvas); 
    }
    
    
    public boolean onTouchEvent(MotionEvent event) {
    
          switch (event.getAction()) {
             case MotionEvent.ACTION_DOWN: {
               ViewGroup parentView = (ViewGroup)SelectorView.this.getParent();
               parentView.setX(100);
               parentView.setY(100);
               break;
              }
           }
           return true; 
    }
    
    }