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;
}
}
A ViewGroup is a special view that can contain other views. The ViewGroup is the base class for Layouts in android, like LinearLayout , RelativeLayout , FrameLayout etc. In other words, ViewGroup is generally used to define the layout in which views(widgets) will be set/arranged/listed on the android screen.
In android (and most other technologies), views can have subviews, aka "children". Most views can have children and can be a child of a parent view. It's kind of like a "tree". The most obvious feature of being a child of some other view is that the child moves with the parent view.
A ViewGroup is a special view that can contain other views (called children.) The view group is the base class for layouts and views containers. This class also defines the ViewGroup. LayoutParams class which serves as the base class for layouts parameters.
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;
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With