我想MyView
通过按一个按钮来改变大小。
的初始大小MyView
是 400 * 400,每次我按下按钮b1
,w
增加 100。我想视图大小应该改变,但它仍然是 400 * 400。但是,如果我改变按钮的大小b2
,ClickListener
(添加行 a和 b) 行,大小b2
和MyView
更改大小。我不知道这是怎么回事。如果我只想MyView
动态改变大小,我该怎么办?
相关代码:
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;
}
}