I have an activity with 3 views (buttonViews) in a vertical linear layout. I am generating (inflating) these views dynamically. I want to apply an animation such that, on activity start, the first buttons slide in -> 100 ms delay -> second button slide in -> 100 ms delay -> Third button slide in.
Attempt
I tried implementing it in this way:
private void setMainButtons() {
ArrayList<String> dashboardTitles = DashboardUtils.getDashboardTitles();
ArrayList<Integer> dashboardIcons = DashboardUtils.getDashboardIcons();
final ViewGroup root = findViewById(R.id.button_container);
for (int i = 0; i < (dashboardTitles.size() < dashboardIcons.size() ? dashboardTitles.size() : dashboardIcons.size()); i++){
final View buttonView = DashboardButtonInflater.getDashboardButton(root, dashboardTitles.get(i), dashboardIcons.get(i), this);
if (buttonView == null) continue;
buttonView.setOnClickListener(this);
root.addView(buttonView);
animateBottomToTop(buttonView, (long) (i*50)); // Calling method to animate buttonView
}
}
//The function that adds animation to buttonView, with a delay.
private void animateBottomToTop(final View buttonView,long delay) {
AnimationSet animationSet = new AnimationSet(false);
animationSet.addAnimation(bottomToTop);
animationSet.addAnimation(fadeIn);
animationSet.setStartOffset(delay);
buttonView.setAnimation(animationSet);
}
Result:
The above method waits for the total delay of all the views and at the end, aminates all the views together. I can guess the culprit here is the thread. The dealy is actually stopping the UI thread from doing any animation. I could be wrong though.
I also tried running the animation code inside
new Thread(new Runnable(){...}).run()
but that didn't work either.
Expectations:
Can somebody help me achieve the one-by-one animation on buttonView? Thank you.
Animations are statefull objects, you should not use the same instance multiple times simultaneously. In your case the bottomToTop and fadeIn animations are shared between the animation sets. When the set starts (initialize() is called) it will set the start offset of its children.
For example the method could look like :
//The function that adds animation to buttonView, with a delay.
private void animateBottomToTop(final View buttonView,long delay) {
AnimationSet animationSet = new AnimationSet(false);
// create new instances of the animations each time
animationSet.addAnimation(createBottomToTop());
animationSet.addAnimation(createFadeIn());
animationSet.setStartOffset(delay);
buttonView.setAnimation(animationSet);
}
The problem might be easily solved with Transitions API. Having declared a root layout with this xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/content_frame"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"/>
Then inside activity:
class MainActivity : AppCompatActivity() {
lateinit var content: LinearLayout
private var counter = 0
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
content = findViewById(R.id.content_frame)
// wait this view to be laid out and only then start adding and animating views
content.post { addNextChild() }
}
private fun addNextChild() {
// terminal condition
if (counter >= 3) return
++counter
val button = createButton()
val slide = Slide()
slide.duration = 500
slide.startDelay = 100
slide.addListener(object : TransitionListenerAdapter() {
override fun onTransitionEnd(transition: Transition) {
addNextChild()
}
})
TransitionManager.beginDelayedTransition(content, slide)
content.addView(button)
}
private fun createButton(): Button {
val button = Button(this)
button.layoutParams = ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT)
button.text = "button"
return button
}
}
This chunk of code will result in following output:
You can adjust animation and delay times respectively.
If you want following behavior:
Then you can use following code:
class MainActivity : AppCompatActivity() {
lateinit var content: LinearLayout
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
content = findViewById(R.id.content_frame)
content.post { addChildren() }
}
private fun addChildren() {
val button1 = createButton()
val button2 = createButton()
val button3 = createButton()
val slide1 = Slide()
slide1.duration = 500
slide1.addTarget(button1)
val slide2 = Slide()
slide2.duration = 500
slide2.startDelay = 150
slide2.addTarget(button2)
val slide3 = Slide()
slide3.duration = 500
slide3.startDelay = 300
slide3.addTarget(button3)
val set = TransitionSet()
set.addTransition(slide1)
set.addTransition(slide2)
set.addTransition(slide3)
TransitionManager.beginDelayedTransition(content, set)
content.addView(button1)
content.addView(button2)
content.addView(button3)
}
private fun createButton(): Button {
val button = Button(this)
button.layoutParams = ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT)
button.text = "button"
return button
}
}
Create method, which will accept Any number of Animation to invoke one after another. Just as example.
private void playOneAfterAnother(#NonNull Queue<Animation> anims) {
final Animation next = anims.poll();
/* You can set any other paramters,
like delay, for each next Playing view, if any of course */
next.addListener(new AnimationListener() {
#Override
public void onAnimationEnd(Animator a) {
if (!anim.isEmpty()) {
playOneAfterAnother(anims);
}
}
#Override
public void onAnimationStart(Animator a) {
}
#Override
public void onAnimationCancel(Animator a) {
}
#Override
public void onAnimationRepeat(Animator a) {
}
});
next.play();
}
Or with delay for animations, it's easy too.
private void playOneAfterAnother(#NonNull Queue<Animation> anims,
long offsetBetween, int nextIndex) {
final Animation next = anims.poll();
/* You can set any other paramters,
like delay, for each next Playing view, if any of course */
next.setStartOffset(offsetBetween * nextIndex);
next.play();
if (!anim.isEmpty()) {
playOneAfterAnother(anims,
offsetBetween, nextIndex +1);
}
}
Probably, what you need to use is AnimatorSet instead of AnimationSet. The AnimatorSet API allows you to choreograph animations in two ways:
1. PlaySequentially
2. PlayTogether
using the apis:
AnimatorSet animatorSet = new AnimatorSet();
animatorSet.playSequentially(anim1, anim2, anim3, ...);
animatorSet.playTogether(anim1, anim2, anim3, ...);
You can further add delays to your animation using
animatorSet.setStartDelay();
Visit the complete API docs here https://developer.android.com/reference/android/animation/AnimatorSet
Hope this helps!
I Use This Code And its work correctly
Hope to help you
// first put your views in an array with name arrayViews
final int[] time = {0};
for (int i = 0; i < arrayViews.size(); i++) {
Animation zoom = AnimationUtils.loadAnimation(this, R.anim.fade_in);
zoom.setDuration(250);
zoom.setStartOffset(time[0] += 250);
arrayViews.get(i).startAnimation(zoom);
arrayViews.get(i).setVisibility(View.VISIBLE);
}
When i call setVisibility on view's child while the (parent) view is animated with ViewCompat.postOnAnimation things get broken. (setVisibility doesn't work + some other things get broken).
Question - is there any method of animation or workaround which allows to call setVisibility on child while the parent is animated?
This is very important request and i think not so unusual, because for example http request is returned in random time, and the view can be animated anytime during that.
Code request edit:
Regarding code, it is bit complicated. I will first explain. It is animation in the custom CoordinatorLayout Behavior, clone of the standard BottomSheetBehavior (sliding of sheet from bottom to up).
Animation is launched by calling this:
ViewCompat.postOnAnimation(child, new SettleRunnable(child, targetState));
SettleRunnable is this:
private class SettleRunnable implements Runnable {
private final View mView;
#State
private final int mTargetState;
SettleRunnable(View view, #State int targetState) {
mView = view;
mTargetState = targetState;
}
#Override
public void run() {
if (mViewDragHelper != null && mViewDragHelper.continueSettling(true)) {
ViewCompat.postOnAnimation(mView, this);
} else {
setStateInternal(mTargetState);
}
}
}
So as you can see, all the animation movement is done by mViewDragHelper.continueSettling. Drag helper is standard class ViewDragHelper.
ViewDragHelper.continueSettling looks like this
public boolean continueSettling(boolean deferCallbacks) {
if (mDragState == STATE_SETTLING) {
boolean keepGoing = mScroller.computeScrollOffset();
final int x = mScroller.getCurrX();
final int y = mScroller.getCurrY();
final int dx = x - mCapturedView.getLeft();
final int dy = y - mCapturedView.getTop();
if (dx != 0) {
ViewCompat.offsetLeftAndRight(mCapturedView, dx);
}
if (dy != 0) {
ViewCompat.offsetTopAndBottom(mCapturedView, dy);
}
if (dx != 0 || dy != 0) {
mCallback.onViewPositionChanged(mCapturedView, x, y, dx, dy);
}
if (keepGoing && x == mScroller.getFinalX() && y == mScroller.getFinalY()) {
// Close enough. The interpolator/scroller might think we're still moving
// but the user sure doesn't.
mScroller.abortAnimation();
keepGoing = false;
}
if (!keepGoing) {
if (deferCallbacks) {
mParentView.post(mSetIdleRunnable);
} else {
setDragState(STATE_IDLE);
}
}
}
return mDragState == STATE_SETTLING;
}
It simply animates the sheet up or down to desired position according the chosen target state.
Pseudo code of problem is:
launchAnimation(); // it takes eg 300 ms
changeVisibilityOfAnimatedViewChildren(); // this is problem
I can wait until the animation finishes, but as i said, in case of http request it is bit problem, i would like to ideally refresh the data right away without waiting.
Animated element is CoordinatorLayout. Affected child by setVisibility is one or more its children.
Judging by this link, android seems to have generally problem with animations and setVisibility.
Possible solutions i am thinking of now:
Maybe if i would change the visibility with another parallel postOnAnimation() task (?)
Or because it are basically just step by step subsequent calls of moving function mViewDragHelper.continueSettling() why don't do it without postOnAnimation()? I could run the task also without it. But i guess that postOnAnimation chooses some correct delay of animation step for concrete device + probably some other things.
You can add AnimatorListenerAdapter to your parent animation, and override onAnimationEnd() method. In this method you can call the child animation. However, I would rather change alpha of view than visibility. You can achieve more smoothly effect in this case.
For example, consider this code:
parentAnimationInstance.addListener(new AnimatorListenerAdapter() {
#Override
public void onAnimationEnd(Animator animation) {
super.onAnimationEnd(animation);
childView.animate()
.alpha(1.f)
.setDuration(200)
.start();
}
});
I have two horizontal scrollview, and want to keep them always at the same position / distance. If user scrolls one, need to scroll programmatically the other. The challenge is, that an infinite loop will occur. One will raise the other, other will raise first. How can I set a state, indicate that a user initiated scroll is still in progress? So other scrollview should not execute the programmatic scroll.
One of them is a HorizontalScrollView other is a RecyclerView.
Tried solutions like below, without any success:
horizontalScrollView.getViewTreeObserver().addOnScrollChangedListener(new ViewTreeObserver.OnScrollChangedListener() {
#Override
public void onScrollChanged() {
if (programmaticScrollEnable) {
programmaticScrollEnable = false;
// do programmatic scrolling here
programmaticScrollEnable = true;
}
}
});
Tried to change state in onScrollStateChanged method:
#Override
public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
super.onScrollStateChanged(recyclerView, newState);
/*if (newState == RecyclerView.SCROLL_STATE_IDLE) {
MainActivity.programmaticScrollEnable = true;
}*/
}
Try this...
horizontalScrollView.getViewTreeObserver().addOnScrollChangedListener(new ViewTreeObserver.OnScrollChangedListener() {
#Override
public void onScrollChanged() {
recyclerView.scrollTo(horizontalScrollView.scrollTo(horizontalScrollView.getScrollX(), 0);
}
});
The challenge is, that an infinite loop will occur.
You can avoid the infinite loop by registering the last touched ScrolledView in OnTouchListener. This touched ScrollView must not scroll programmatically; but the other(s) should be.
This can be tracked by setting a tag to each ScrollView and compare that tag during scroll event.
If you are API level 23 (Android M), you can register View.OnScrollChangeListener. And for APIs below that, you can register ViewTreeObserver.OnScrollChangedListener. But the latter is heavy on the resources; so you need to handle that.
For API levels 23+
// Tracking last touched SV
private var touchedSVTag = -1
// list of ScrollViews
val svs = arrayListOf(scrollview1, scrollview2)
val scrollListener =
View.OnScrollChangeListener { view, scrollX, _, _, _ ->
val currentSVTag = view!!.tag as Int
if (currentSVTag == touchedSVTag) {
for (svTag in 0 until svs.size)
if (svTag != currentSVTag)
svs[svTag].scrollTo(scrollX, 0)
}
}
val itemTouchListener = View.OnTouchListener { sv, _ ->
val svTag = sv.tag as Int
if (touchedSVTag != -1 && touchedSVTag != svTag) {
// stop scrollView in the middle of the scroll
svs[touchedSVTag].fling(0)
}
touchedSVTag = svTag
false
}
for (i in 0 until svs.size) {
val sv = svs[i]
sv.tag = i
sv.setOnScrollChangeListener(scrollListener)
sv.setOnTouchListener(itemTouchListener)
}
And for API levels below 23:
// Tracking last touched SV
private var touchedSVTag = -1
// list of ScrollViews
val svs = arrayListOf(scrollview1, scrollview2)
val scrollListener = {
val scrolledSV = svs[touchedSVTag]
for (svTag in 0 until svs.size)
if (svTag != touchedSVTag)
svs[svTag].scrollTo(scrolledSV.scrollX, 0)
}
val itemTouchListener = View.OnTouchListener { sv, _ ->
val svTag = sv.tag as Int
if (touchedSVTag != -1 && touchedSVTag != svTag) {
// stop scrollView in the middle of the scroll
svs[touchedSVTag].fling(0)
}
touchedSVTag = svTag
false
}
for (i in 0 until svs.size) {
val sv = svs[i]
sv.tag = i
sv.viewTreeObserver.addOnScrollChangedListener(scrollListener)
sv.setOnTouchListener(itemTouchListener)
}
I am creating all of the elements in my android project dynamically. I am trying to get the width and height of a button so that I can rotate that button around. I am just trying to learn how to work with the android language. However, it returns 0.
I did some research and I saw that it needs to be done somewhere other than in the onCreate() method. If someone can give me an example of how to do it, that would be great.
Here is my current code:
package com.animation;
import android.app.Activity;
import android.os.Bundle;
import android.view.animation.Animation;
import android.view.animation.LinearInterpolator;
import android.view.animation.RotateAnimation;
import android.widget.Button;
import android.widget.LinearLayout;
public class AnimateScreen extends Activity {
//Called when the activity is first created.
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
LinearLayout ll = new LinearLayout(this);
LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
layoutParams.setMargins(30, 20, 30, 0);
Button bt = new Button(this);
bt.setText(String.valueOf(bt.getWidth()));
RotateAnimation ra = new RotateAnimation(0,360,bt.getWidth() / 2,bt.getHeight() / 2);
ra.setDuration(3000L);
ra.setRepeatMode(Animation.RESTART);
ra.setRepeatCount(Animation.INFINITE);
ra.setInterpolator(new LinearInterpolator());
bt.startAnimation(ra);
ll.addView(bt,layoutParams);
setContentView(ll);
}
Any help is appreciated.
The basic problem is, that you have to wait for the drawing phase for the actual measurements (especially with dynamic values like wrap_content or match_parent), but usually this phase hasn't been finished up to onResume(). So you need a workaround for waiting for this phase. There a are different possible solutions to this:
1. Listen to Draw/Layout Events: ViewTreeObserver
A ViewTreeObserver gets fired for different drawing events. Usually the OnGlobalLayoutListener is what you want for getting the measurement, so the code in the listener will be called after the layout phase, so the measurements are ready:
view.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
#Override
public void onGlobalLayout() {
view.getViewTreeObserver().removeOnGlobalLayoutListener(this);
view.getHeight(); //height is ready
}
});
Note: The listener will be immediately removed because otherwise it will fire on every layout event. If you have to support apps SDK Lvl < 16 use this to unregister the listener:
public void removeGlobalOnLayoutListener (ViewTreeObserver.OnGlobalLayoutListener victim)
2. Add a runnable to the layout queue: View.post()
Not very well known and my favourite solution. Basically just use the View's post method with your own runnable. This basically queues your code after the view's measure, layout, etc. as stated by Romain Guy:
The UI event queue will process events in order. After
setContentView() is invoked, the event queue will contain a message
asking for a relayout, so anything you post to the queue will happen
after the layout pass
Example:
final View view=//smth;
...
view.post(new Runnable() {
#Override
public void run() {
view.getHeight(); //height is ready
}
});
The advantage over ViewTreeObserver:
your code is only executed once and you don't have to disable the Observer after execution which can be a hassle
less verbose syntax
References:
https://stackoverflow.com/a/3602144/774398
https://stackoverflow.com/a/3948036/774398
3. Overwrite Views's onLayout Method
This is only practical in certain situation when the logic can be encapsulated in the view itself, otherwise this is a quite verbose and cumbersome syntax.
view = new View(this) {
#Override
protected void onLayout(boolean changed, int l, int t, int r, int b) {
super.onLayout(changed, l, t, r, b);
view.getHeight(); //height is ready
}
};
Also mind, that onLayout will be called many times, so be considerate what you do in the method, or disable your code after the first time
4. Check if has been through layout phase
If you have code that is executing multiple times while creating the ui you could use the following support v4 lib method:
View viewYouNeedHeightFrom = ...
...
if(ViewCompat.isLaidOut(viewYouNeedHeightFrom)) {
viewYouNeedHeightFrom.getHeight();
}
Returns true if view has been through at least one layout since it was
last attached to or detached from a window.
Additional: Getting staticly defined measurements
If it suffices to just get the statically defined height/width, you can just do this with:
View.getMeasuredWidth()
View.getMeasuredHeigth()
But mind you, that this might be different to the actual width/height after drawing. The javadoc describes the difference in more detail:
The size of a view is expressed with a width and a height. A view
actually possess two pairs of width and height values.
The first pair is known as measured width and measured height. These
dimensions define how big a view wants to be within its parent (see
Layout for more details.) The measured dimensions can be obtained by
calling getMeasuredWidth() and getMeasuredHeight().
The second pair is simply known as width and height, or sometimes
drawing width and drawing height. These dimensions define the actual
size of the view on screen, at drawing time and after layout. These
values may, but do not have to, be different from the measured width
and height. The width and height can be obtained by calling getWidth()
and getHeight().
We can use
#Override
public void onWindowFocusChanged(boolean hasFocus) {
super.onWindowFocusChanged(hasFocus);
//Here you can get the size!
}
You are calling getWidth() too early. The UI has not been sized and laid out on the screen yet.
I doubt you want to be doing what you are doing, anyway -- widgets being animated do not change their clickable areas, and so the button will still respond to clicks in the original orientation regardless of how it has rotated.
That being said, you can use a dimension resource to define the button size, then reference that dimension resource from your layout file and your source code, to avoid this problem.
I used this solution, which I think is better than onWindowFocusChanged(). If you open a DialogFragment, then rotate the phone, onWindowFocusChanged will be called only when the user closes the dialog):
yourView.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
#Override
public void onGlobalLayout() {
// Ensure you call it only once :
yourView.getViewTreeObserver().removeGlobalOnLayoutListener(this);
// Here you can get the size :)
}
});
Edit : as removeGlobalOnLayoutListener is deprecated, you should now do :
#SuppressLint("NewApi")
#SuppressWarnings("deprecation")
#Override
public void onGlobalLayout() {
// Ensure you call it only once :
if(android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.JELLY_BEAN) {
yourView.getViewTreeObserver().removeOnGlobalLayoutListener(this);
}
else {
yourView.getViewTreeObserver().removeGlobalOnLayoutListener(this);
}
// Here you can get the size :)
}
If you need to get width of some widget before it is displayed on screen, you can use getMeasuredWidth() or getMeasuredHeight().
myImage.measure(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
int width = myImage.getMeasuredWidth();
int height = myImage.getMeasuredHeight();
As Ian states in this Android Developers thread:
Anyhow, the deal is that layout of the
contents of a window happens
after all the elements are constructed and added to their parent
views. It has to be this way, because
until you know what components a View
contains, and what they contain, and
so on, there's no sensible way you can
lay it out.
Bottom line, if you call getWidth()
etc. in a constructor, it will return
zero. The procedure is to create all
your view elements in the constructor,
then wait for your View's
onSizeChanged() method to be called --
that's when you first find out your
real size, so that's when you set up
the sizes of your GUI elements.
Be aware too that onSizeChanged() is
sometimes called with parameters of
zero -- check for this case, and
return immediately (so you don't get a
divide by zero when calculating your
layout, etc.). Some time later it
will be called with the real values.
I would rather use OnPreDrawListener() instead of addOnGlobalLayoutListener(), since it is called a bit earlier than other listeners.
view.getViewTreeObserver().addOnPreDrawListener(new ViewTreeObserver.OnPreDrawListener()
{
#Override
public boolean onPreDraw()
{
if (view.getViewTreeObserver().isAlive())
view.getViewTreeObserver().removeOnPreDrawListener(this);
// put your code here
return true;
}
});
Adjusted the code according to comment of #Pang. onPreDraw method should return true to proceed with the current drawing pass.
AndroidX has multiple extension functions that help you with this kind of work, inside androidx.core.view
You need to use Kotlin for this.
The one that best fits here is doOnLayout:
Performs the given action when this view is laid out. If the view has been laid out and it has not requested a layout, the action will be performed straight away otherwise, the action will be performed after the view is next laid out.
The action will only be invoked once on the next layout and then removed.
In your example:
bt.doOnLayout {
val ra = RotateAnimation(0,360,it.width / 2,it.height / 2)
// more code
}
Dependency: androidx.core:core-ktx:1.0.0
A Kotlin Extension to observe on the global layout and perform a given task when height is ready dynamically.
Usage:
view.height { Log.i("Info", "Here is your height:" + it) }
Implementation:
fun <T : View> T.height(function: (Int) -> Unit) {
if (height == 0)
viewTreeObserver.addOnGlobalLayoutListener(object : ViewTreeObserver.OnGlobalLayoutListener {
override fun onGlobalLayout() {
viewTreeObserver.removeOnGlobalLayoutListener(this)
function(height)
}
})
else function(height)
}
It happens because the view needs more time to be inflated. So instead of calling view.width and view.height on the main thread, you should use view.post { ... } to make sure that your view has already been inflated. In Kotlin:
view.post{width}
view.post{height}
In Java you can also call getWidth() and getHeight() methods in a Runnable and pass the Runnable to view.post() method.
view.post(new Runnable() {
#Override
public void run() {
view.getWidth();
view.getHeight();
}
});
One liner if you are using RxJava & RxBindings. Similar approach without the boilerplate. This also solves the hack to suppress warnings as in the answer by Tim Autin.
RxView.layoutChanges(yourView).take(1)
.subscribe(aVoid -> {
// width and height have been calculated here
});
This is it. No need to be unsubscribe, even if never called.
Maybe this helps someone:
Create an extension function for the View class
filename: ViewExt.kt
fun View.afterLayout(what: () -> Unit) {
if(isLaidOut) {
what.invoke()
} else {
viewTreeObserver.addOnGlobalLayoutListener(object : ViewTreeObserver.OnGlobalLayoutListener {
override fun onGlobalLayout() {
viewTreeObserver.removeOnGlobalLayoutListener(this)
what.invoke()
}
})
}
}
This can then be used on any view with:
view.afterLayout {
do something with view.height
}
Height and width are zero because view has not been created by the time you are requesting it's height and width .
One simplest solution is
view.post(new Runnable() {
#Override
public void run() {
view.getHeight(); //height is ready
view.getWidth(); //width is ready
}
});
This method is good as compared to other methods as it is short and crisp.
If you are using Kotlin
customView.viewTreeObserver.addOnGlobalLayoutListener(object : ViewTreeObserver.OnGlobalLayoutListener {
override fun onGlobalLayout() {
if(android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.JELLY_BEAN) {
customView.viewTreeObserver.removeOnGlobalLayoutListener(this)
}
else {
customView.viewTreeObserver.removeGlobalOnLayoutListener(this)
}
// Here you can get the size :)
viewWidth = customView.width
}
})
Answer with post is incorrect, because the size might not be recalculated.
Another important thing is that the view and all it ancestors must be visible. For that I use a property View.isShown.
Here is my kotlin function, that can be placed somewhere in utils:
fun View.onInitialized(onInit: () -> Unit) {
viewTreeObserver.addOnGlobalLayoutListener(object : OnGlobalLayoutListener {
override fun onGlobalLayout() {
if (isShown) {
viewTreeObserver.removeOnGlobalLayoutListener(this)
onInit()
}
}
})
}
And the usage is:
myView.onInitialized {
Log.d(TAG, "width is: " + myView.width)
}
For Kotlin:
I have faced a production crash due to use view.height/ view.width which lead to NaN while I was using View.post() which sometimes view diemsions returned with 0 value.
So,
Use view.doOnPreDraw { // your action here} which is:
OneShotPreDrawListener so it called only one time.
Implements OnPreDrawListener which make sure view is layouted and measured
well , you can use addOnLayoutChangeListener
you can use it in onCreate in Activity or onCreateView in Fragment
#Edit
dont forget to remove it because in some cases its trigger infinite loop
myView.addOnLayoutChangeListener(object : View.OnLayoutChangeListener{
override fun onLayoutChange(
v: View?, left: Int, top: Int, right: Int, bottom: Int, oldLeft: Int, oldTop: Int, oldRight: Int, oldBottom: Int
) {
if (v?.width > 0 && v?.height > 0){
// do something
Log.i(TAG, "view : ${view.width}")
// remove after finish
v?.removeOnLayoutChangeListener(this)
}
}
})
Cleanest way of doing this is using post method of view :
kotlin:
view.post{
var width = view.width
var height = view.height
}
Java:
view.post(new Runnable() {
#Override
public void run() {
int width = view.getWidth();
int height = view.getHeight();
}
});
Gone views returns 0 as height if app in background.
This my code (1oo% works)
fun View.postWithTreeObserver(postJob: (View, Int, Int) -> Unit) {
viewTreeObserver.addOnGlobalLayoutListener(object : ViewTreeObserver.OnGlobalLayoutListener {
override fun onGlobalLayout() {
val widthSpec = View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED)
val heightSpec = View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED)
measure(widthSpec, heightSpec)
postJob(this#postWithTreeObserver, measuredWidth, measuredHeight)
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN) {
#Suppress("DEPRECATION")
viewTreeObserver.removeGlobalOnLayoutListener(this)
} else {
viewTreeObserver.removeOnGlobalLayoutListener(this)
}
}
})
}
We need to wait for view will be drawn. For this purpose use OnPreDrawListener. Kotlin example:
val preDrawListener = object : ViewTreeObserver.OnPreDrawListener {
override fun onPreDraw(): Boolean {
view.viewTreeObserver.removeOnPreDrawListener(this)
// code which requires view size parameters
return true
}
}
view.viewTreeObserver.addOnPreDrawListener(preDrawListener)
In my case, I can't get a view's height by post or by addOnGlobalLayoutListener, it's always 0. Because my view is in a fragment, and the fragment is the second tab in MainActivity. when I open MainActivity, I enter the first tab, so the second tab doesn't show on the screen. But onGlobalLayout() or post() function still has a callback.
I get the view's height when the second fragment is visible on the screen. And this time I get the correct height.
Usage:
imageView.size { width, height ->
//your code
}
View extention:
fun <T : View> T.size(function: (Int, Int) -> Unit) {
if (isLaidOut && height != 0 && width != 0) {
function(width, height)
} else {
if (height == 0 || width == 0) {
var onLayoutChangeListener: View.OnLayoutChangeListener? = null
var onGlobalLayoutListener: ViewTreeObserver.OnGlobalLayoutListener? = null
onGlobalLayoutListener = object : ViewTreeObserver.OnGlobalLayoutListener {
override fun onGlobalLayout() {
if (isShown) {
removeOnLayoutChangeListener(onLayoutChangeListener)
viewTreeObserver.removeOnGlobalLayoutListener(this)
function(width, height)
}
}
}
onLayoutChangeListener = object : View.OnLayoutChangeListener {
override fun onLayoutChange(
v: View?,
left: Int,
top: Int,
right: Int,
bottom: Int,
oldLeft: Int,
oldTop: Int,
oldRight: Int,
oldBottom: Int
) {
val width = v?.width ?: 0
val height = v?.height ?: 0
if (width > 0 && height > 0) {
// remove after finish
viewTreeObserver.removeOnGlobalLayoutListener(onGlobalLayoutListener)
v?.removeOnLayoutChangeListener(this)
function(width, height)
}
}
}
viewTreeObserver.addOnGlobalLayoutListener(onGlobalLayoutListener)
addOnLayoutChangeListener(onLayoutChangeListener)
} else {
function(width, height)
}
}
}
public final class ViewUtils {
public interface ViewUtilsListener {
void onDrawCompleted();
}
private ViewUtils() {
}
public static void onDraw(View view, ViewUtilsListener listener) {
view.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
#Override
public void onGlobalLayout() {
if (view.getHeight() != 0 && view.getWidth() != 0) {
if (listener != null) {
listener.onDrawCompleted();
}
view.getViewTreeObserver().removeOnGlobalLayoutListener(this);
}
}
});
}
}
you can use like this ;
ViewUtils.onDraw(view, new ViewUtils.ViewUtilsListener() {
#Override
public void onDrawCompleted() {
int width = view.getWidth();
int height = view.getHeight();
}
});
private val getWidth: Int
get() {
if (Build.VERSION.SDK_INT >= 30) {
val windowMetrics =windowManager.currentWindowMetrics
val bounds = windowMetrics.bounds
var adWidthPixels = View.width.toFloat()
if (adWidthPixels == 0f) {
adWidthPixels = bounds.width().toFloat()
}
val density = resources.displayMetrics.density
val adWidth = (adWidthPixels / density).toInt()
return adWidth
} else {
val display = windowManager.defaultDisplay
val outMetrics = DisplayMetrics()
display.getMetrics(outMetrics)
val density = outMetrics.density
var adWidthPixels = View.width.toFloat()
if (adWidthPixels == 0f) {
adWidthPixels = outMetrics.widthPixels.toFloat()
}
val adWidth = (adWidthPixels / density).toInt()
return adWidth
}
}
replace (View) with the view you want to measure
This is a little old, but was having trouble with this myself (needing to animate objects in a fragment when it is created). This solution worked for me, I believe it is self explanatory.
class YourFragment: Fragment() {
var width = 0
var height = 0
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
// Inflate the layout for this fragment
val root = inflater.inflate(R.layout.fragment_winner_splash, container, false)
container?.width.let {
if (it != null) {
width = it
}
}
container?.height.let {
if (it != null) {
height = it
}
}
return root
}
If you're worried about overworking the onDraw method, you can always set the dimension as null during construction and then only set the dimension inside of onDraw if it's null.
That way you're not really doing any work inside onDraw
class myView(context:Context,attr:AttributeSet?):View(context,attr){
var height:Float?=null
override fun onDraw(canvas:Canvas){
if (height==null){height=this.height.toFloat()}
}
}