2012-01-09 29 views
3

我正在通過將形狀和句柄作爲單獨視圖添加到ViewGroup來創建可伸縮形狀。點擊一個處理程序後,如何獲得對ViewGroup的引用,以便我可以縮放所有內容? handle.getParent()返回null。我的ViewGroup是以編程方式創建的。獲取對父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; 
    } 

} 
+0

請發表您使用添加手柄的代碼和響應點擊。 – 2012-01-09 04:10:00

+0

添加更多詳情 – KcYxA 2012-01-09 04:38:40

+0

請添加處理點擊的代碼。 – 2012-01-09 04:44:02

回答

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

} 
+0

謝謝!!!!!! – KcYxA 2012-01-09 06:08:18