Android_Layout 用代码得到对象的高宽
当设定 ViewGroup.LayoutParams 的设定优先。
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button button = new Button(getApplicationContext());
button.setText("Button");
// ViewGroup.LayoutParams layoutParams = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
ViewGroup.LayoutParams layoutParams = new ViewGroup.LayoutParams(500, 500);
ViewGroup viewGroup = (ViewGroup) findViewById(R.id.activity_main);
button.setHeight(400);
button.setWidth(400);
// viewGroup.addView(button);
viewGroup.addView(button, layoutParams);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
RelativeLayout.LayoutParams rl = (RelativeLayout.LayoutParams) ((Button) v).getLayoutParams();
System.out.println(rl.height);
System.out.println(rl.width);
System.out.println(((Button) v).getHeight());
System.out.println(((Button) v).getWidth());
}
});
}
当>>>>
ViewGroup.LayoutParams layoutParams = new ViewGroup.LayoutParams(500, 500);
ViewGroup viewGroup = (ViewGroup) findViewById(R.id.activity_main);
button.setHeight(400);
button.setWidth(400);
viewGroup.addView(button, layoutParams);
结果
I/System.out: 500
I/System.out: 500
I/System.out: 500
I/System.out: 500
当>>>>
button.setText("Button");
// ViewGroup.LayoutParams layoutParams = new ViewGroup.LayoutParams(500, 500);
ViewGroup viewGroup = (ViewGroup) findViewById(R.id.activity_main);
button.setHeight(400);
button.setWidth(400);
viewGroup.addView(button);
结果
I/System.out: -2
I/System.out: -2
I/System.out: 400
I/System.out: 400
0 件のコメント:
コメントを投稿