Reputation: 3535
I want to construct a generic function which receives a LinearLayout (or another view) and calculate the empty space left in it, so i know how many space i've to fit something into it
The main purpose of it is to set ads, example:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:ads="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/mainView"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".activity.MainActivity">
<TextView
android:layout_width="match_parent"
android:layout_height="@dimen/profilePhotoRadius"
/>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="@dimen/smallMargin"
android:layout_marginTop="@dimen/smallMargin"
/>
<!-- bunch of other stuff here -->
<com.google.android.gms.ads.AdView
android:id="@+id/adView"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1"
android:layout_alignParentBottom="true"/>
</LinearLayout>
then after in my code
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
this.adView = (AdView) findViewById(R.id.adView);
if (this.adView != null) {
int width = this.adView.getMeasuredWidth();
int height = this.adView.getHeight();
}
but running this code width
and height
are always zero... i tried to use getWidth()
and result is always zero
how can i get the real value?
Upvotes: 2
Views: 226
Reputation: 427
In OnCreate()
you are are just inflating the layout. The UI has not been sized and laid out on the screen yet.You are calling getWidth()
and getHeight()
too early.
You can try this:
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
this.adView = (AdView) findViewById(R.id.adView);
this.adView.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
@Override
public void onGlobalLayout() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
touchView.getViewTreeObserver().removeOnGlobalLayoutListener(this);
}
else {
touchView.getViewTreeObserver().removeGlobalOnLayoutListener(this);
}
float Width = this.adView.getWidth();
float Height =this.adView.getHeight();
...
}
});
Upvotes: 2
Reputation:
Try it in onWindowFocusChanged (boolean hasFocus)
method.
From the documentation:
This is the best indicator of whether this activity is visible to the user
Upvotes: 0