获取对父ViewGroup的引用

时间:2012-01-09 04:05:07

标签: android shapes viewgroup

我通过向ViewGroup添加形状和句柄作为单独的视图来创建可伸缩的形状。单击处理程序后,如何获取对ViewGroup的引用以便我可以扩展所有内容? handle.getParent()返回null。我的ViewGroup是以编程方式创建的。

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

}

1 个答案:

答案 0 :(得分:7)

请使用SelectorView.this.getParent()代替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; 
}

}