我想使用的getWidth()/ getHeight()都会让我的XML-布局的宽度/高度。 我读书,我必须这样做,在的方法OnSizeChanged(),否则我会得到0 (Android:获取屏幕分辨率/像素的整数值的)。
I want to use getWidth()/getHeight() to get width/height of my XML-Layout. I read I have to do it in the method onSizeChanged() otherwise I will get 0 ( Android: Get the screen resolution / pixels as integer values ).
不过,我想这样做在一个类中已经延伸活动。 因此,我认为这是不可能让同一个类扩展视图。
But I want to do it in a class already extending Activity. So I think it's not possible let the same class extending View.
public class MyClass extends Activity {
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
ViewGroup xml_layout = (ViewGroup) findViewById(R.id.layout_id);
TextView tv = new TextView(this);
tv = (TextView) findViewById(R.id.text_view);
int layout_height = xml_layout.getHeight();
int layout_width = xml_layout.getWidth();
}
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
//Error, because I need to use extends View for class, but I can't do it because I also need extends Activity to use onCreate
}
}
如果我用MyClass的延伸活动,我可以使用的onCreate但不能onSizeChanged。 如果我使用MyClass的扩展视图我可以使用onSizeChangedbut没有的onCreate。
If I use MyClass extends Activity I can use onCreate but not onSizeChanged. If I use MyClass extends View I can use onSizeChangedbut not onCreate.
我该如何解决这个问题呢?
How can I solve the problem?
你不必创建一个 customView
来获取其高度和宽度。您可以添加OnLayoutChangedListener(description这里)的观点,其宽度/你想要的高度,然后基本上得到了onLayoutChanged方法的价值,像这样
You dont have to create a customView
to get its height and width. You can add an OnLayoutChangedListener (description here) to the view whose width/height you want, and then essentially get the values in the onLayoutChanged method, like so
View myView = findViewById(R.id.my_view);
myView.addOnLayoutChangeListener(new OnLayoutChangeListener() {
@Override
public void onLayoutChange(View v, int left, int top, int right, int bottom, int oldLeft, int oldTop, int oldRight,
int oldBottom) {
// its possible that the layout is not complete in which case
// we will get all zero values for the positions, so ignore the event
if (left == 0 && top == 0 && right == 0 && bottom == 0) {
return;
}
// Do what you need to do with the height/width since they are now set
}
});
这样做的原因是因为次绘制后才布局完成。然后,系统将走下视图层次结构树绘制之前,测量每个视图的宽度/高度。
The reason for this is because views are drawn only after the layout is complete. The system then walks down the view heirarchy tree to measure the width/height of each view before drawing them.