Home » Android » How to get width of the container in which my view is added in Android

How to get width of the container in which my view is added in Android

Posted by: admin May 14, 2020 Leave a comment

Questions:

I have a ImageView object inside a LinearLayout. I’m setting an animation to the ImageView which will move image view from point x to y. Now, starting point should be right corner of parent container. My question is , how do i get the dimension of the container in which the view is present. I don’t see view.getParent().getWidth() kind of method in view hierachy.

How to&Answers:

Perhaps you don’t need to because you can use % for animation like this:

<set xmlns:android="http://schemas.android.com/apk/res/android" android:interpolator="@android:anim/accelerate_interpolator">
<translate android:fromXDelta="100%p" android:toXDelta="0" android:duration="150" />

Answer:

Try this:

View parent = (View)view.getParent();
int width = parent.getWidth();

Answer:

Call after view added in a parent view, otherwise you would this exeption
java.lang.NullPointerException: Attempt to invoke virtual method ‘int android.view.View.getHeight()’

    int height = ((View) view.getParent()).getHeight();
    int width = ((View) view.getParent()).getWidth();

    int mHeight = ((View) view.getParent()).getMeasuredHeight();
    int mWidth = ((View) view.getParent()).getMeasuredWidth();