I have a circle at the center of the screen inside which there's an ImageView + TextView. I have another two ImageView+TextView, one at the top and another at bottom of the screen.
My requirement is :
I want a copy of the top ImageView+TextView and a copy of the bottom ImageView+TextView to move in animation into the center of the circle, thereby changing the value of the textView inside the circle.
For example:
Say top textView has value 200 and bottom textview has value 300. I want a portion of those values (say 100 or 150) to animate and move into the circle, but the original values 200 and 300 should remain on the same position.
I've tried using TranslateAnimation. However I face issues finding the x and y coordinates of the center circle. It is not exactly going to the center of the circle. Also original view's position is not retained.
TranslateAnimation animation = new
TranslateAnimation(startLayout.getX(),endLayout.getX(),
startLayout.getY(),endLayout.getY);
animation.setDuration(1000);
animation.setFillAfter(false);
startView.startAnimation(animation);
startLayout is the linearlayout in which ImageView and TextView reside.
Please help! Thanks!
I had the same issue and I fixed by using the next code (sorry is in Kotlin, but works the same in Java).Let's say viewFirst wants to reach viewTwo position:
(DON'T USE):
viewFirst.animate()
.translationX(viewSecond.x)
.translationY(viewSecond.y)
.setDuration(1000)
.withEndAction {
//to make sure that it arrives,
//but not needed actually these two lines
viewFirst.x = viewSecond.x
viewFirst.y = viewSecond.y
}
.start()
(USE THIS SOLUTION):
viewFirst.animate()
.x(viewSecond.x)
.y(viewSecond.y)
.setDuration(1000)
.withEndAction {
//to make sure that it arrives,
//but not needed actually these two lines
viewFirst.x = viewSecond.x
viewFirst.y = viewSecond.y
}
.start()
Using the getX() and getY() methods define the position of the view in pixels, but the constructor you use defines Float type values that must be values from 0.0f to 1.0f
TranslateAnimation(float fromXDelta, float toXDelta, float fromYDelta, float toYDelta)
This is another option using the view`s position in pixels:
viewFirst.animate()
.x(viewSecond.getX())
.y(viewSecond.getY())
.setDuration(1000).withEndAction(new Runnable() {
#Override
public void run() {
viewFirst.setX(tv2.getX());
viewFirst.setY(tv2.getY());
}
}).start();
Try this for accurate coordinates
private fun moveView(viewToBeMoved: View, targetView: View) {
val targetX: Float =
targetView.x + targetView.width / 2 - viewToBeMoved.width / 2
val targetY: Float =
targetView.y + targetView.height / 2 - viewToBeMoved.height / 2
viewToBeMoved.animate()
.x(targetX)
.y(targetY)
.setDuration(2000)
.withEndAction {
targetView.visibility = View.GONE
}
.start()
}
Related
I am trying to implement TapToFocus feature using the CameraX Api .I have implemented it successfully but not able to know how to draw a circle on the preview describing the Location pressed by the user .
I want to have a circle in the preview like the image has
The are many ways to draw and animate a focus ring around a tap position on PreviewView, some fancier than others. One simple way of doing so is to:
Create a Drawable of the ring, something like this for instance.
Layout an ImageView containing the Drawable on top of PreviewView, and initially hide it.
<FrameLayout ...>
<androidx.camera.view.PreviewView
... />
<ImageView
android:id="#+id/focusRing"
android:src="#drawable/focus_ring"
android:visibility="invisible"
... />
</FrameLayout>
Set up a touch listener on PreviewView. On a touch event, use the event's coordinates to show the ring around it.
private void animateFocusRing(float x, float y) {
ImageView focusRing = findViewById(R.id.focusRing);
// Move the focus ring so that its center is at the tap location (x, y)
float width = focusRing.getWidth();
float height = focusRing.getHeight();
focusRing.setX(x - width / 2);
focusRing.setY(y - height / 2);
// Show focus ring
focusRing.setVisibility(View.VISIBLE);
focusRing.setAlpha(1F);
// Animate the focus ring to disappear
focusRing.animate()
.setStartDelay(500)
.setDuration(300)
.alpha(0F)
.setListener(new Animator.AnimatorListener() {
#Override
public void onAnimationEnd(Animator animator) {
focusRing.setVisibility(View.INVISIBLE);
}
// The rest of AnimatorListener's methods.
});
}
HI i have the below animation for a view below:
val duration = 2000L
val visible = 1.0f
imageAVater.apply {
animate().translationYBy(-100f).alpha(visible).setDuration(duration).setListener(object : AnimatorListenerAdapter(){
override fun onAnimationEnd(animation: Animator?) {
visibility = View.VISIBLE
}
})
}
i want it to move from slightly off-position and into position and to also reveal itself by setting the alpha .
SO far neither works.
ALl the code above does is move the image from current default position on my layout(lets say i positioned it in xml along the Y axis position 200) and then it moves from position 200 to position 100 and also the alpha does not work, the item is visible all the time despite it being set to View.Gone in my xml
android:visibility="gone"
How can i set a start and end Y axis value for this translation animation and how can i get the alpha to work so that the view appears from hidden/gone?
i want it to start at 200 y and have it transition to 100 y and to also reveal itself from being hidden/gone to being shown at the same time as the transition
you need to specify starting values for y and alpha. EG.
imageAVater.apply {
alpha = 0f
animate().alpha(1f).setDuration(2000).start()
}
leave the view's visibility always to visible. You can not animate a view that is gone
I have a View that has an OnClickListener. When clicked, the view translates up to a certain position on the page. This is no problem, the view goes where it should. When the view is clicked again, I would like to position it somewhere else, but this is not the case. After a little bit of trouble shooting, I found that my View's getTop() method returns the same value - even after the translation animation has moved the view to a different part of the screen. For the second animation, it is not using the current position (as I would expect), it instead uses the initial position.
Few things that I am doing: I am using the ObjectAnimation class rather than the TranslationAnimation class, since I wanted to keep the OnClickListener functioning. With the TranslationAnimation class, I found that the view was correctly moved, but the OnClickListener was only working in the area that the View started from. Using the ObjectAnimation class, I was able to easily get the translation to work AND the OnClickListener functions correctly - it is triggered where the view currently is on the screen.
Here's what I have so far:
final LinearLayout child = layouts.get(i); //ArrayList containing some dynamic layouts
final int offset = target - child.getTop();
ObjectAnimator anim = ObjectAnimator.ofFloat(child,"translationY",offset);
anim.setDuration(250);
anim.start();
This is what happens when the view is clicked the first time. It translates up along the Y axis, where the offset determines how far the View needs to move from its current position.
Now, here's what happens on the second click. The goal here was to align the view with the parent's base.
target = parent.getBottom();
offset = target - child.getTop();
anim = ObjectAnimator.ofFloat(child, "translationY",offset);
anim.setDuration(250);
anim.start();
prev = child;
This is where things fall apart - child.getTop() returns the Y coordinate of the view's ORIGINAL position. Not the current position. So after the animation, the view is placed well below the bottom of the parent. I read a different question which stated that I should use child.getY() instead, which is supposed to give me the translationY position plus the top position, but this didn't lead to any better results. I can't seem to get this to work just right. I'd simply like to move the view from its current position to the bottom of the screen, but this appears to be a hard thing to accomplish. Any help would be appreciated.
EDIT
I have added an animation listener:
ObjectAnimator anim = ObjectAnimator.ofFloat(child,"translationY",offset);
anim.setDuration(250);
anim.addListener(new ObjectAnimator.AnimatorListener(){
#Override
public void onAnimationStart(Animator animation) {
System.out.println("start: " + child.getTop() + " " + child.getY());
}
#Override
public void onAnimationEnd(Animator animation) {
System.out.println("end: " + child.getTop() + " " + child.getY() + " " + child.getTranslationY());
child.setTop((int)child.getY());
System.out.println(child.getTop());
}
#Override
public void onAnimationCancel(Animator animation) {}
#Override
public void onAnimationRepeat(Animator animation) {}
});
anim.start();
Here I am setting the listener to try to change where the Top of the view is located. Behaviour is again not working as expected. The view is actually sent up above the screen when I do this. Output of the System.out looks like this:
start: 2008 2008.0
end: 2008 478.0 -1530.0
478
So calling child.getTop() after the animation is complete and setting a new position returns a positive integer, but the view is not actually completely on screen. It is above the screen, partly visible. The height of the view itself is about 700px. I am still so confused as to why this is such a hard thing to accomplish.
EDIT 2
I have also tried setting layoutparams inside the onAnimationEnd method:
RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams)child.getLayoutParams();
params.removeRule(RelativeLayout.ALIGN_PARENT_BOTTOM);
params.addRule(RelativeLayout.ALIGN_PARENT_TOP, RelativeLayout.TRUE);
params.topMargin = (int)child.getY();
child.setLayoutParams(params);
Result: child.getTop() still returns the original position of 2008.
You can get the very bottom of the screen coordinates like this :
float bottomOfScreen = getResources().getDisplayMetrics().heightPixels;
but you probably want it minus the height of your LinearLayout or else your LinearLayout will be cut off by the bottom :
float bottomOfScreen = getResources().getDisplayMetrics().heightPixels
- child.getHeight();
// if you want a little more space to the bottom
// try something like - child.getHeight()*2;
Then use ViewPropertyAnimator to animate your LL like this :
child.animate()
.translationY(bottomOfScreen)
.setInterpolator(new AccelerateDecelerateInterpolator())
.setDuration(250);
The Interpolator is just to make the animation more realistic.
In the case that child.getHeight() returns 0 , your Linear Layout has not been finished setting up by the system, in that case you might want to do something like :
child.post(new Runnable() {
#Override
public void run() {
float bottomOfScreen = getResources().getDisplayMetrics().heightPixels
- child.getHeight()*2;
child.animate()
.translationY(bottomOfScreen)
.setInterpolator(new AccelerateDecelerateInterpolator())
.setDuration(250);
}
});
Remember that a duration of 250 milliseconds is very fast, and does usually not look cool translating stuff on the screen, so you might want to set it a little higher, but thats just a matter of taste.
I have a LinearLayout (LayoutContentView) which can contain one or two view (SubView1 and SubView2) (they are eitherTextView or ImageView).
This layout is in another LinearLayout (MyScreenLayout).
I want to make an animation on LayoutContentView so it can move and show just a part of it in MyScreenLayout.
Both of these layouts have setClipChildren(false); so it can let it's children draw outside it-self.
Depending on different parameters, I can change the size of the content, and the size of the content I will show.
Basically, I expend from top to bottom to show the two subviews and unexpend for bottom to top to show only the second subview. Before I expend, I increase the size of the LayoutContentView, so it can show the two subviews, and after I unexpend, I decrease the size of the LayoutContentView, so it can only show the second subview, and it let space on the screen for other elements.
Here is my method for expending and un-expending LayoutContentView :
mLayoutContentView.clearAnimation();
float yFrom = 0.0F;
float yTo = 0.0F;
float xFrom = 0.0F;
float xTo = 0.0F;
if (expend) { // if we expend
// I change the height of my LayoutContentView so it we can show it's two subviews
final android.view.ViewGroup.LayoutParams lp = mLayoutContentView.getLayoutParams();
lp.height = subView1H + subView2H;
setLayoutParams(lp);
invalidate();
// we start the animation so it shows only the second subview
yFrom = -subView1H;
// and we animate from top to bottom until it shows the two subviews
yTo = 0;
} else { // if we un-expend
// we animate from bottom to top starting by showing the two subviews
yFrom = 0;
// and progressively hiding the first subview and showing only the second subview
yTo = -subView1H;
}
Animation anim = new TranslateAnimation(xFrom, xTo, yFrom, yTo);
anim.setDuration(1000);
anim.setFillAfter(true);
anim.setFillEnabled(true);
anim.setAnimationListener(new AnimationListener() {
#Override
public void onAnimationStart(Animation animation) {
}
#Override
public void onAnimationRepeat(Animation animation) {
}
#Override
public void onAnimationEnd(Animation animation) {
if (!expend) {
// if we un expend at the end of the animation we can set the size of LayoutContentView to the size of the second subview again
final android.view.ViewGroup.LayoutParams lp = mLayoutContentView.getLayoutParams();
lp.height = subView2H;
mLayoutContentView.setLayoutParams(lp);
invalidate();
}
}
});
mLayoutContentView.startAnimation(anim);
The way I made my animation I need it to apply on LayoutContentView, the layout which contain two subview, and with startAnimation() it doesn't do the animation.
I tried to use a LayoutAnimationController, but instead of doing the animation on the LayoutContentView, it does it on each of its children...
I also tried to do the animation on each children myself, but I don't know why, the second subview isn't shown.
Each time I've tried to use HierarchyViewer, but it's does see the change made by the animation.
Does anyone know a solution or have faced the same problem and found a good solution ?
EDIT :
Well it seems that if you set a background color to your TextView and move them with animation, the background move but even if you have set the fill after parameter to your animation, the background moves back to it's original position or something like that, and therefore as I set a background color to both of my SubViews, somewhat one of the SubView's background hide the background of the other...
And there also a problem if after the animation, one of the SubView is still outside the its layout, there is also a problem during the animation, so I add a limitation to what I intended to here too.
I have a button that I want to put on a 45 degree angle. For some reason I can't get this to work.
Can someone please provide the code to accomplish this?
API 11 added a setRotation() method to all views.
You could create an animation and apply it to your button view. For example:
// Locate view
ImageView diskView = (ImageView) findViewById(R.id.imageView3);
// Create an animation instance
Animation an = new RotateAnimation(0.0f, 360.0f, pivotX, pivotY);
// Set the animation's parameters
an.setDuration(10000); // duration in ms
an.setRepeatCount(0); // -1 = infinite repeated
an.setRepeatMode(Animation.REVERSE); // reverses each repeat
an.setFillAfter(true); // keep rotation after animation
// Aply animation to image view
diskView.setAnimation(an);
Extend the TextView class and override the onDraw() method. Make sure the parent view is large enough to handle the rotated button without clipping it.
#Override
protected void onDraw(Canvas canvas) {
canvas.save();
canvas.rotate(45,<appropriate x pivot value>,<appropriate y pivot value>);
super.onDraw(canvas);
canvas.restore();
}
I just used the simple line in my code and it works :
myCusstomView.setRotation(45);
Hope it works for you.
One line in XML
<View
android:rotation="45"
... />
Applying a rotation animation (without duration, thus no animation effect) is a simpler solution than either calling View.setRotation() or override View.onDraw method.
// substitude deltaDegrees for whatever you want
RotateAnimation rotate = new RotateAnimation(0f, deltaDegrees,
Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f);
// prevents View from restoring to original direction.
rotate.setFillAfter(true);
someButton.startAnimation(rotate);
Rotating view with rotate() will not affect your view's measured size. As result, rotated view be clipped or not fit into the parent layout. This library fixes it though:
https://github.com/rongi/rotate-layout
Joininig #Rudi's and #Pete's answers. I have created an RotateAnimation that keeps buttons functionality also after rotation.
setRotation() method preserves buttons functionality.
Code Sample:
Animation an = new RotateAnimation(0.0f, 180.0f, mainLayout.getWidth()/2, mainLayout.getHeight()/2);
an.setDuration(1000);
an.setRepeatCount(0);
an.setFillAfter(false); // DO NOT keep rotation after animation
an.setFillEnabled(true); // Make smooth ending of Animation
an.setAnimationListener(new AnimationListener() {
#Override
public void onAnimationStart(Animation animation) {}
#Override
public void onAnimationRepeat(Animation animation) {}
#Override
public void onAnimationEnd(Animation animation) {
mainLayout.setRotation(180.0f); // Make instant rotation when Animation is finished
}
});
mainLayout.startAnimation(an);
mainLayout is a (LinearLayout) field
As mentioned before, the easiest way it to use rotation available since API 11:
android:rotation="90" // in XML layout
view.rotation = 90f // programatically
You can also change pivot of rotation, which is by default set to center of the view. This needs to be changed programatically:
// top left
view.pivotX = 0f
view.pivotY = 0f
// bottom right
view.pivotX = width.toFloat()
view.pivotY = height.toFloat()
...
In Activity's onCreate() or Fragment's onCreateView(...) width and height are equal to 0, because the view wasn't measured yet. You can access it simply by using doOnPreDraw extension from Android KTX, i.e.:
view.apply {
doOnPreDraw {
pivotX = width.toFloat()
pivotY = height.toFloat()
}
}
if you wish to make it dynamically with an animation:
view.animate()
.rotation(180)
.start();
THATS IT
#Ichorus's answer is correct for views, but if you want to draw rotated rectangles or text, you can do the following in your onDraw (or onDispatchDraw) callback for your view:
(note that theta is the angle from the x axis of the desired rotation, pivot is the Point that represents the point around which we want the rectangle to rotate, and horizontalRect is the rect's position "before" it was rotated)
canvas.save();
canvas.rotate(theta, pivot.x, pivot.y);
canvas.drawRect(horizontalRect, paint);
canvas.restore();
fun rotateArrow(view: View): Boolean {
return if (view.rotation == 0F) {
view.animate().setDuration(200).rotation(180F)
true
} else {
view.animate().setDuration(200).rotation(0F)
false
}
}
That's simple,
in Java
your_component.setRotation(15);
or
your_component.setRotation(295.18f);
in XML
<Button android:rotation="15" />