Android: grow/shrink View over time - android

I have a view layout like this:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="fill_parent"
android:layout_height="fill_parent" android:background="#color/light_gray"
android:padding="5dip">
<View android:id="#+id/fixedSpace" android:layout_width="fill_parent"
android:layout_height="50dip" android:background="#color/aqua"
android:layout_alignParentBottom="true" android:clickable="true"
android:onClick="onClickStartAnimation" />
<View android:id="#+id/dynamicSpace" android:layout_width="fill_parent"
android:layout_height="200dip" android:background="#color/lime"
android:layout_above="#id/fixedSpace" />
<View android:id="#+id/remainingSpace" android:layout_width="fill_parent"
android:layout_height="fill_parent" android:background="#color/pink"
android:layout_alignParentTop="true" android:layout_above="#id/dynamicSpace" />
</RelativeLayout>
What I want to achieve is basically a grow/shrink behavior of dynamicSpace over the time t. With animations I can produce the following:
t=1:
t=2:
t=3:
However, that doesn't really resize my views, in particular dynamicSpace and remainingSpace. It just animates the view dynamicSpace moving in. But the view "container" already has the space occupied right from the beginning.
Correct would be that the lime colored dynamicSpace starts with 0px and the pink colored remainingSpace takes over, so there is no gray space in between.

Scale the View
Since you say you are doing it over time t, it sounds like a LinearInterpolator is best.

EDIT:
I tried replacing the below with an AsyncTask thread and it is far smoother. I think the key is I keep the thread running in the background and just use it when I want to resize something, thus reducing overhead
Create a custom AnimationListener and put the code for resizing the view in the onAnimationRepeat method.
Then do a dummy animation and set repeat on the animation to infinite. Once the view has reached the final size, set repeat count on the animation to zero (again in onAnimationRepeat):
class ResizeAnimationListener implements AnimationListener{
int finalHeight; // max Height
int resizeAmount; // amount to resize each time
View view; // view to resize
public ResizeAnimationListener(int finalHeight; View view, int resizeAmount) {
super();
finalHeight; = finalHeight;
this.resizeAmount = resizeAmount;
this.view = view;
}
#Override
public void onAnimationEnd(Animation animation) {
}
#Override
public void onAnimationRepeat(Animation animation) {
int newHeight;
int currentHeight;
current = view.getMeasuredHeight();
newHeight= currentHeight+ resizeAmount;
if(newHeight> finalHeight){
// check if reached final height
// set new height to the final height
newHeight = finalHeight;
// set repeat count to zero so we don't have any more repeats
anim.setRepeatCount(0);
}
// set new height
LayoutParams params = view.getLayoutParams();
params.height = newHeight;
v.setLayoutParams(params);
}
#Override
public void onAnimationStart(Animation animation) {
}
};
class DummyAnimation extends Animation{}
float frameRate = 1000/30;
DummyAnimation anim = new DummyAnimation();
anim.setDuration((long)frameRate);
anim.setRepeatCount(Animation.INFINITE);
ResizeAnimationListener animListener = new ResizeAnimationListener(((View)view.getParent()).getHeight(), view, 25);
anim.setAnimationListener(animListener);
view.startAnimation(anim);
I made this work on my own app . However, views anchored to the view I'm resizing (and thus moving on screen when I resize my view) seem to glitch out. Probably related to repeated resizing rather than anything else, but just a warning. Maybe someone else knows why?

Related

View width is zero when set to MATCH_PARENT

I have an ImageView inside of a LinearLayout which is an item of a RecyclerView. I have all these views' width as MATCH_PARENT.
Now, I'm trying to calculate the heigth using the aspect ratio before the image is loaded so there's no resizing.
But, what I've seen is that before the image is loaded, its width is zero.
The thing is that I'm doing similar things in other parts of the app and it's working fine, I don't really know what I'm missing here.
RecyclerView item:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#android:color/white">
<LinearLayout
...
</LinearLayout>
<!-- This is the image -->
<ImageView
android:id="#+id/descubre_shop_banner"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_margin="16dp"
android:adjustViewBounds="true"
android:scaleType="centerCrop"/>
<View
android:layout_width="match_parent"
android:layout_height="1dp"
android:background="#color/colorLightText"
android:layout_marginRight="16dp"
android:layout_marginLeft="16dp"
android:layout_marginBottom="8dp"/>
</LinearLayout>
ViewHolder
mBannerTarget = new Target()
{
#Override
public void onBitmapLoaded(Bitmap bitmap, Picasso.LoadedFrom from)
{
mShopBannerImageView.setImageBitmap(bitmap);
// Wrap content when the images is loaded.
mShopBannerImageView.getLayoutParams().height = ViewGroup.LayoutParams.WRAP_CONTENT;
mShopBannerImageView.setBackgroundColor(-1);
mShopBannerImageView.setAlpha(1.0f);
Animation fadeOut = new AlphaAnimation(0, 1);
fadeOut.setInterpolator(new AccelerateInterpolator());
fadeOut.setDuration(250);
mShopBannerImageView.startAnimation(fadeOut);
LOADED = true;
}
#Override
public void onBitmapFailed(Drawable errorDrawable)
{
mShopBannerImageView.setBackgroundColor(
mContext.getResources().getColor(android.R.color.holo_red_dark));
mShopBannerImageView.setAlpha(0.2f);
}
#Override
public void onPrepareLoad(Drawable placeHolderDrawable)
{
// This is 0
Log.d(Properties.TAG, "" + mShopBannerImageView.getWidth());
// Remove the old bitmap
mShopBannerImageView.setImageBitmap(null);
// Set the height using the width and the aspect ratio.
mShopBannerImageView.getLayoutParams().height =
(int) (mShopBannerImageView.getWidth() * shop.getAspectRatio());
// Set a color while loading.
mShopBannerImageView.setBackgroundColor(
mContext.getResources().getColor(R.color.colorAccent));
mShopBannerImageView.setAlpha(0.25f);
}
};
I tried to set the width of the ImageView and its parent as MATCH_PARENT in code but no luck. Any clue of what's going on?
Regards,
The views dimensions is always 0 before being fully created, if you wanted to know the actual width, you have to use the method: post():
view.post(new Runnable() {
#Override
public void run() {
// This is where width would be different than 0
}
});
That being said, you should actually use an other method to keep the ratio than actually calculating it yourself!
See this thread for further information How to scale an Image in ImageView to keep the aspect ratio

Ripple effect animation without touching

I need to do some like ripple effect of Listview item background changing. I try to use ObjectAnimator like this:
AnimatorSet set = (AnimatorSet) AnimatorInflater.loadAnimator(activity,
R.animator.animator_bkg);
set.setTarget(childLinear);
set.setInterpolator(new AccelerateInterpolator());
set.start();
R.animator.animator_bkg:
<objectAnimator
android:propertyName="backgroundColor"
android:duration="3000"
android:valueFrom="#color/white"
android:valueTo="#color/redTrans"
android:repeatCount="-1"
android:repeatMode="reverse"/>
It fluently changes a background (complete filling), but I need gradual filling of ListView item like ripple effect after touch the button.
I think, maybe I can use Canvas with overriding onDraw, but it's to hard for application and it can be some lags.
You can do it with a custom view and implement the circular transition in onDraw(), but it's complicated.
You can work around the complexity by using ViewAnimationUtils.createCircularReveal() on sub view. But the draw back is that it's only for API 21+.
In few words, your root layout of the cell has to be a FrameLayout or a RelativeLayout.
When the transition starts, you dynamically add 2 views under your cell with the start and the end color, then transition with the circular reveal between the 2. At the end of the transition, you just remove the 2 sub views to keep the view hierarchy a bit cleaner.
Here is the result :
In code :
Cell layout:
<FrameLayout
android:id="#+id/cell_root"
android:layout_width="match_parent"
android:layout_height="72dp">
<LinearLayout
android:id="#+id/cell_content"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:padding="16dp"
android:background="#FF00FF">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Title"
android:textSize="18sp" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="This is content"
android:textSize="14sp" />
</LinearLayout>
</FrameLayout>
Code that trigger the background transition :
private void changeBackgroundColor() {
final FrameLayout startingColorFrame = new FrameLayout(mCellRoot.getContext());
final FrameLayout endingColorFrame = new FrameLayout(mCellRoot.getContext());
startingColorFrame.setBackground(mCellContent.getBackground());
endingColorFrame.setBackground(mPendingColor);
mCellContent.setBackground(null);
endingColorFrame.setVisibility(View.GONE);
mCellRoot.addView(endingColorFrame, 0, new FrameLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
mCellRoot.addView(startingColorFrame, 0, new FrameLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
int finalRadius = (int) Math.sqrt(mCellRoot.getWidth()*mCellRoot.getWidth() + mCellRoot.getHeight()*mCellRoot.getHeight());
final int sourceX = mCellRoot.getWidth() / 3;
final int sourceY = mCellRoot.getHeight() / 2;
// this is API 21 minimum. Add proper checks
final Animator circularReveal = ViewAnimationUtils.createCircularReveal(endingColorFrame, sourceX, sourceY, 0, finalRadius);
endingColorFrame.setVisibility(View.VISIBLE);
circularReveal.addListener(new AnimatorListenerAdapter() {
#Override
public void onAnimationEnd(final Animator animation) {
super.onAnimationEnd(animation);
mStartButton.setEnabled(true);
mCellContent.setBackground(mPendingColor);
mPendingColor = startingColorFrame.getBackground();
mCellRoot.removeView(startingColorFrame);
mCellRoot.removeView(endingColorFrame);
}
});
// customize the animation here
circularReveal.setDuration(800);
circularReveal.setInterpolator(new AccelerateInterpolator());
circularReveal.start();
}

Updating view position after animation

I'm working on getting a animation to work. I'm moving a search bar from the middle of the screen to the top of the screen. The animation works fine, but once it's moved I can't interact with anything. I've updated the position but can't interact with it regardless. Here's what I've got so far:
private void moveSearchToTop()
{
FrameLayout root = (FrameLayout) findViewById( R.id.rootLayout );
DisplayMetrics dm = new DisplayMetrics();
this.getWindowManager().getDefaultDisplay().getMetrics( dm );
statusBarOffset = dm.heightPixels - root.getMeasuredHeight();
int originalPos[] = new int[2];
mSearchBar.getLocationOnScreen( originalPos );
search_top = statusBarOffset - originalPos[1];
TranslateAnimation anim = new TranslateAnimation( 0, 0, 0, search_top);
anim.setDuration(500);
anim.setFillAfter(true);
anim.setAnimationListener(new Animation.AnimationListener() {
#Override
public void onAnimationStart(Animation animation) {
}
#Override
public void onAnimationEnd(Animation animation) {
mSearchBar.layout(0, search_top, 0, mSearchBar.getHeight() + search_top);
}
#Override
public void onAnimationRepeat(Animation animation) {
}
});
mSearchBar.startAnimation(anim);
}
and here's what the view looks like in xml:
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="center_vertical"
android:id="#+id/search_bar"
android:background="#android:drawable/dialog_holo_light_frame">
<ImageView
android:id="#+id/search_icon"
android:layout_width="wrap_content"
android:onClick="onSearchClick"
android:layout_height="25dp"
android:layout_gravity="center_vertical"
android:src="#drawable/search"/>
<EditText
android:id="#+id/search_field"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_vertical"
android:layout_weight="1"
android:singleLine="true"
android:hint="Search"/>
<ImageView
android:layout_width="wrap_content"
android:layout_height="25dp"
android:layout_gravity="center_vertical"
android:src="#drawable/camera"/>
</LinearLayout>
Do I need to update the position of all of the child elements too? Thanks for a push in the right position.
No, you won't need to modify the child views. They will go where the search bar goes.
It looks to me like you are using your search_top variable both as a delta (for the TranslateAnimation constructor) and as a position within its parent (in the call to layout). It's really a delta, so the call to layout is incorrect.
Is the parent of your searchBar the "root" FrameLayout? If so, then you just want to use 0 as the new y coordinate in the call to layout. Also, you are using 0 as the right coordinate, which means that it has no width after the animation. This call would position your search bar at the upper-left edge of its parent, and maintain its current width and height:
mSearchBar.layout(0, 0, mSearchBar.getWidth(), mSearchBar.getHeight());
I also would recommend that you do not use screen position. It's safer to just set the position of views within parent views. For example, if the search bar's parent really is root, then you could get the delta with:
search_top = - mSearchBar.getTop();

Translate a View from One Layout to Another with Translate Animation

I am new in Android animation and my requirement is to translate a view from one layout to layout in a single xml file on click of that view.
Scenario:
Suppose I click a button, present on the top of the header in a xml file,and it should move/translate downwards (it should give an impact that it lies on the other layout downwards to header), and also I want that when the user clicks on the same again, it should now move to its original position.
Here I am explaining with my xml file:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#drawable/app_bg"
android:orientation="vertical" >
<RelativeLayout
android:id="#+id/top"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:background="#drawable/header"
android:paddingLeft="10dp"
android:paddingRight="10dp" >
<Button
android:id="#+id/btnSearchHeader"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
android:layout_centerInParent="true"
android:background="#drawable/search_icon" />
</RelativeLayout>
<RelativeLayout
android:id="#+id/bottom"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="#color/app_transparent"
android:paddingLeft="10dp"
android:paddingRight="10dp"
android:layout_marginTop="10dp"
android:visibility="visible" >
<Button
android:id="#+id/btnMenu"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_centerVertical="true"
android:layout_marginRight="5dp"
android:text="ABC" />
<Button
android:id="#+id/btnSearchSelected"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
android:layout_toRightOf="#+id/btnMenu"
android:text="CDE" />
</RelativeLayout>
</LinearLayout>
MORE PRECISE REQUIREMENT SPECIFICATION (Kindly read carefully:)
Here I have two sub inner layouts:-
Top Layout - id-> top
Bottom Layout- id -> bottom
Now a view (Button -> btnSearchHeader) is lying in my top layout and I want to animate the same to the bottom layout (it should give an impact that it is translated with a translate animation to the bottom layout) on click of that button and when the user clicks on that button, it should again translate back to its original position with a translate animation .. i.e it should show back in the top layout
I have no idea how to give these impacts using translate animations, however i just have a basic translate animation knowledge which is insufficient for me to work upon my requirement.
Any type of related help is appreciable.
Thanks
Have you tried something simple like the following?
final int topHeight = findViewById(R.id.top).getHeight();
final int bottomHeight = findViewById(R.id.bottom).getHeight();
final View button = findViewById(R.id.btnSearchHeader);
final ObjectAnimator moveDownAnim = ObjectAnimator.ofFloat(button, "translationY", 0.F, topHeight + bottomHeight / 2 - button.getHeight() / 2);
final ObjectAnimator moveUpAnim = ObjectAnimator.ofFloat(button, "translationY", topHeight + bottomHeight / 2 - button.getHeight() / 2, 0.F);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (0.F == v.getTranslationY())
moveDownAnim.start();
else
moveUpAnim.start();
}
});
If you actually need the button view to change parents, you can use AnimatorListener to achieve this at the end of each animation. Something like:
moveDownAnim.addListener(new Animator.AnimatorListener() {
#Override
public void onAnimationEnd(Animator animation) {
((ViewGroup)findViewById(R.id.top)).removeView(button);
((ViewGroup)findViewById(R.id.bottom)).addView(button);
((RelativeLayout)button.getLayoutParams()).addRule(RelativeLayout.CENTER_IN_PARENT);
button.setTranslationY(0.F); // Since it is now positioned in the new layout, no need for translation.
}
#Override
public void onAnimationCancel(Animator animation) { /* NOP */ }
#Override
public void onAnimationRepeat(Animator animation) { /* NOP */ }
#Override
public void onAnimationStart(Animator animation) { /* NOP */ }
});
(And analogous listener for the moveUpAnim.)
However, I doubt you need to actually do this to achieve the visual effect you want. But if you do this part, you will probably also need to set a fixed height for your top view as opposed to wrap_content. (Otherwise, if a layout pass happens while the button has been moved to the bottom view, the top layout's height might go to 0 if there's nothing else in it.) Easiest would be to just do this directly in the xml layout file. However, if you want to "do it on the fly", you can change the layout's height in the onAnimationEnd() method using something like:
#Override
public void onAnimationEnd(Animator animation) {
final ViewGroup topLayout = findViewById(R.id.top);
topLayout.getLayoutParams().height = topLayout.getHeight(); // Keep it the same height...
topLayout.removeView(button);
((ViewGroup)findViewById(R.id.bottom)).addView(button);
((RelativeLayout)button.getLayoutParams()).addRule(RelativeLayout.CENTER_IN_PARENT);
button.setTranslationY(0.F); // Since it is now positioned in the new layout, no need for translation.
}

getWidth and getHeight are returning a zero

I am trying to make a simple drawing program for the android.
I have a custom View class to handle the drawing. When I call its getWidth and getHeight metheds, I get a zero.
But, the drawing works fine, I hard code in the width and height so it works. Why is it doing this?
My View class
public class cDrawing extends View{
char BitMap[];
static final short WIDTH=160;
static final short HEIGHT=440;
static final char EMPTY=' ';
int mWidthSize;
int mHeightSize;
static final char RED ='R';
int y;
public cDrawing(Context context) {
super(context);
y=3;
// set up our bitmap
BitMap=new char[WIDTH*HEIGHT];
for(int i=0; i<WIDTH*HEIGHT; i++)
BitMap[i]=EMPTY;
// returns zero why???????
int h=getHeight();
h=400;
int w=getWidth();
w=320;
mWidthSize=w/WIDTH;
mHeightSize=h/HEIGHT;
// TODO Auto-generated constructor stub
}
The Activity class
public class cCanves extends Activity implements OnClickListener {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.canves);
cDrawing board=new cDrawing(this);
LinearLayout layout = (LinearLayout)findViewById(R.id.parent2);
layout.addView(board);
// set up buttons
View mEraser = findViewById(R.id.buteraser);
mEraser.setOnClickListener(this);
View mBlack = findViewById(R.id.butblack);
mBlack.setOnClickListener(this);
View mWhite = findViewById(R.id.butwhite);
mWhite.setOnClickListener(this);
View mRed = findViewById(R.id.butred);
mRed.setOnClickListener(this);
} // end function
public void onClick(View v) {
Intent i;
switch(v.getId())
{
case R.id.buteraser:
break;
case R.id.butblack:
break;
case R.id.butwhite:
break;
case R.id.butred:
break;
} // end switch
} // function
}
the xml file
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout android:id="#+id/parent"
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:orientation="vertical"
android:layout_height="fill_parent">
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:orientation="horizontal"
android:layout_height="wrap_content">
<ImageButton android:id="#+id/buteraser"
android:src="#drawable/icon"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
<ImageButton android:id="#+id/butblack"
android:src="#drawable/icon"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
<ImageButton android:id="#+id/butwhite"
android:src="#drawable/icon"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
<ImageButton android:id="#+id/butred"
android:src="#drawable/icon"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
</LinearLayout>
<LinearLayout android:id="#+id/parent2"
android:layout_width="fill_parent"
android:orientation="vertical"
android:layout_height="fill_parent">
</LinearLayout>
</LinearLayout>
The width and height are not defined until the view is actually rendered to the screen.
Use protected abstract void onLayout (boolean changed, int l, int t, int r, int b) (which you override in your activity) to know when the sizes are ready.
Complementing Mah's answer, I found out that you can get the values from parameters, like the code bellow:
ImageView imageProcess = (ImageView) li.inflate(
R.layout.andamento_sinistro_imageprocess, centerLayout, false);
imageProcess.setBackgroundResource(
(isActive)?(R.drawable.shape_processon):(R.drawable.shape_processoff));
RelativeLayout.LayoutParams imageProcessParams =
(RelativeLayout.LayoutParams)imageProcess.getLayoutParams();
imageProcessParams.leftMargin =
(int) (centerPosition - 0.5*imageProcessParams.width);
imageProcessParams.addRule(RelativeLayout.CENTER_VERTICAL);
centerLayout.addView(imageProcess);
The real catch here is the use of the LayoutParams, that have rules yet not processed by the element.
I'm not certain, but it may have something to do with where the code is in the lifecycle of your activity. If you're calling getWidth() and getHeight() before the View is displayed on screen, you'll get a value of 0. I've had that happen to me, too.
I'm not sure if there's a way around this. I had to rely on getting the hardware screen's width and height, instead of the view's width and height. You might end up having to approximate the width and height of your view and hard coding it.
You should call getWidth() and getHeight() in the overrided method onLayout.
Just Use the getViewTreeObserver() Listener, and inside this just
calculate the height and width.
Follow the code :
getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
#Override
public void onGlobalLayout() {
//Do your Stuff calculation , like view.getWidth() ...
});
The view only has dimensions after beeing displayed for the first time.
Other thing:
int h=getHeight();
h=400;
Is useless no ? Is it just for testing ?

Categories

Resources