I want to change the size of MyView
by pressing a button.
The initial size of MyView
is 400 * 400, every time I press button b1
, w
adds 100. I suppose the view size should change, but it remains 400 * 400. However, if I change the size of the button b2
in the ClickListener
, (add line a and line b), both the size of b2
and MyView
change size. I don't know how this happens. If I just want to change the size of MyView
dynamically, what should I do?
Relevant code:
public class MyView extends RelativeLayout {
Button b1;
Button b2;
Context sContext;
public static int i = 0;
private int w = 400;
private int h = 400;
private int w2 = 100;
private int h2 = 100;
public MyView(Context context) {
super(context);
sContext = context;
init();
}
public MyView(Context context, AttributeSet attrs) {
super(context, attrs);
sContext = context;
init();
}
private void init() {
b1 = new Button(sContext);
b2 = new Button(sContext);
addView(b1);
addView(b2);
b1.setBackgroundColor(Color.YELLOW);
b2.setX(500);
b1.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
if (MyView.this.getLayoutParams() == null) {
MyView.this.setLayoutParams(new FrameLayout.LayoutParams(w, h));
} else {
MyView.this.getLayoutParams().width = w;
MyView.this.getLayoutParams().height = h;
}
MyView.this.setBackgroundColor(Color.GREEN);
//b2.setWidth(w2); line a
//b2.setHeight(h2); line b
//MyView.this.invalidate();
w += 100;
w2 += 20;
}
});
}
@Override
protected void onDraw(Canvas canvas) {
//super.onDraw(canvas);
test();
}
private void test() {
b2.setBackgroundColor(Color.BLUE);
b2.setX(200.0f);
Toast.makeText(sContext, ""+i, Toast.LENGTH_SHORT).show();
++i;
}
}