我想知道如何测量视图的尺寸。在我的情况下,它是一个绝对布局。我已经阅读了有关这些问题的答案,但仍然不理解。
这是我的代码:
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
AbsoluteLayout layoutbase = (AbsoluteLayout) findViewById(R.id.layoutbase);
drawOval();
}
public void drawOval(){ //, int screenWidth, int screenHeight){
AbsoluteLayout layoutbase = (AbsoluteLayout) findViewById(R.id.layoutbase);
int screenWidth = layoutbase.getWidth();
int screenHeight = layoutbase.getHeight();
Log.i("MyActivity", "screenWidth: " + screenWidth + ", screenHeight: " +screenHeight);
Coordinates c = new Coordinates(BUTTONSIZE,screenWidth,screenHeight);
...some code ...
((ViewGroup) layoutbase ).addView(mybutton, new AbsoluteLayout.LayoutParams(BUTTONSIZE, BUTTONSIZE, c.mX, c.mY));
mybutton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
showText(mybutton);
}
});
}
public void showText(View button){
int x = findViewById(LAYOUT).getWidth();
int y = findViewById(LAYOUT).getHeight();
Toast message = Toast.makeText(this, "x: " + x , Toast.LENGTH_SHORT);
message.show();
}
getWidth()
命令在showText()
中效果很好,但在drawOval()
中却不起作用。我知道它在那里看起来有点不同,但我也在drawOval()
中使用了int x = findViewById(LAYOUT).getWidth();
版本,而且x/y始终是0
。我真的不明白为什么在早期没有宽度/高度。即使我在绝对布局上实际画一个按钮,getWidth()
也会返回0
。显然,我想在drawOval()
中测量大小。
AbsoluteLayout
已被弃用,不应再使用。请改用密度无关的布局! - Alex Lockwood