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
}
}
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?
onSizeChanged() is called once the size as been calculated. Events don't have to come from users all the time. In this example when android change the size, onSizeChanged() is called. Same thing with onDraw() , when the view should be drawn onDraw() is called.
You can use the window. innerHeight property to get the viewport height, and the window. innerWidth to get its width. let viewportHeight = window.
The width and height can be obtained by calling getWidth() and getHeight().
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With