Gradual Transition between Fragments - android

I recently downloaded the Google Sheets app and I was really interested in the first screen that explained the details of the app so I tried to recreate it.
After some research I decided that it was ViewPager and I implemented it.
But the result was not what I expected.
In the sheets app the color changing was gradual and barely noticeable but in my case the transition is clear(The color scheme used are same as the one in the sheets app).
What is the type of animation applied in the sheets app and how can I replicate it?

The easiest way to do that is to:
Remove backgrounds from Fragments in the ViewPager (I assume you use Fragments inside your ViewPager's Adapter... if not, let me know). And by "remove background" I mean e.g. set it to "#android:color/transparent".
Remove background from the ViewPager itself (also e.g. with setting it's color to transparent).
Put a View that will act as a changing background below (z-wise) your ViewPager. For example like this (without parameters):
<FrameLayout>
<View android:id="#+id/animated_color_view"/>
<android.support.v4.view.ViewPager/>
</FrameLayout>
Create a way to animate background color of the animated_color_view. You can use one of the ways included in the thread linked by REG1 in the comment (edit: the comment has been deleted, but this link points to the same thread). For example like this (the approach was taken from this post):
int[] pageColors = new int[]{Color.RED, Color.GREEN};
int currentColor = pageColors[0];
ValueAnimator colorAnimation;
public void animateToColor(int colorTo) {
if (colorAnimation != null) {
colorAnimation.cancel();
}
colorAnimation = ValueAnimator.ofObject(new ArgbEvaluator(), currentColor, colorTo);
colorAnimation.setDuration(250); // milliseconds
colorAnimation.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
#Override
public void onAnimationUpdate(ValueAnimator animator) {
currentColor = (int) animator.getAnimatedValue();
animatedColorView.setBackgroundColor(currentColor);
}
});
colorAnimation.start();
}
Add an OnPageChangeListener that will call this animating method every time a page is selected.
viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
#Override
public void onPageSelected(int position) {
animateToColor(pageColors[position]);
}
#Override
public void onPageScrollStateChanged(int state) {
}
});
And a little side-note: remember the pageColors array's size must be equal to the number of pages in your ViewPager.

Related

FloatingActionButton icon animation (Android FAB src drawable animation)

I was trying to find documentation about how to create icon animation of FAB's (of the Design support library), after searching a while i couldn't find any information about it and the AnimationDrawable reference in android developers doesn't work for FAB's even if the class is a child of ImageView.
but manage to get a workaround that works just fine.
The technic I used is similar to the one exposed on the DrawableAnimation documentation, and using the Property Animation API doc.
First I use the ValueAnimator class, and an int array containing the ids of the drawables that you're going to use in your animation.
final int[] ids = {R.drawable.main_button_1,R.drawable.main_button_2,R.drawable.main_button_3,R.drawable.main_button_4,R.drawable.main_button_5,R.drawable.main_button_6, R.drawable.main_button_7};
fab = (FloatingActionButton) findViewById(R.id.yourFabID);
valueAnimator = ValueAnimator.ofInt(0, ids.length - 1).setDuration(yourAnimationTime);
valueAnimator.setInterpolator( new LinearInterpolator() /*your TimeInterpolator*/ );
Then set up an AnimationUpdateListener, and define the change in icon behavior with the method FloatinActionButton.setImageDrawable(Drawable yourDrawable).
But the ValueAnimator updates by default every available frame (depending on the load in hardware), but we don't need to redraw the icon if it has already been drawn, so that is why I use the variable "i"; so each icon is drawn only once. (the timing depends on the interpolator you define)
valueAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
int i = -1;
#Override
public void onAnimationUpdate(ValueAnimator animation) {
int animatedValue = (int) animation.getAnimatedValue();
if(i!=animatedValue) {
fab.setImageDrawable(getResources().getDrawable(ids[animatedValue]));
i = animatedValue;
}
}
});
This implementation allows you to play the animation backward with the method ValueAnimator.reverse();
I know is not a pro solution but it's the only one I've figured out to work on all API's supporting the PropertyAnimation. Please, if you know a better solution post it here, if not I hope this post is helpful
You can achieve FAB's src drawable animation quite similarly to other views that use background for AnimationDrawable.
For general views' background drawable animation, see Use AnimationDrawable.
However, you cannot call getBackground() to get FAB's src.
Instead, use getDrawable().
Example:
FloatingActionButton loginButton = findViewById(R.id.loginButton);
loginAnimation = (AnimationDrawable) loginButton.getDrawable();
loginButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
loginAnimation.start();
}
});

ViewPagerIndicator and setOnPageChangeListener

I'd like to change the background color as the user changes pages, for that I need to use ViewPager's setOnPageChangeListener. But it seems that this brakes ViewPagerIndicator, as the indicator is stuck in the first page. Here's the code
viewPager.setOnPageChangeListener(new OnPageChangeListener() {
#Override
public void onPageSelected(int position) {
ColorDrawable[] colors = {new ColorDrawable(backgroundColors[previousPosition]), new ColorDrawable(backgroundColors[position])};
TransitionDrawable trans = new TransitionDrawable(colors);
viewPager.setBackgroundDrawable(trans);
trans.startTransition(200);
previousPosition = position;
}
#Override
public void onPageScrolled(int arg0, float arg1, int arg2) {}
#Override
public void onPageScrollStateChanged(int arg0) {}
});
I ended up using ViewPagerIndicator's setOnPageChangeListener instead of ViewPager's method
mIndicator = (IconPageIndicator)findViewById(R.id.indicator);
mIndicator.setViewPager(viewPager);
The code becomes :
mIndicator.setOnPageChangeListener(new OnPageChangeListener() {
#Override
public void onPageSelected(int position) {
ColorDrawable[] colors = {new ColorDrawable(backgroundColors[previousPosition]), new ColorDrawable(backgroundColors[position])};
TransitionDrawable trans = new TransitionDrawable(colors);
viewPager.setBackgroundDrawable(trans);
trans.startTransition(200);
previousPosition = position;
}
#Override
public void onPageScrolled(int arg0, float arg1, int arg2) {}
#Override
public void onPageScrollStateChanged(int arg0) {}
});
This way of changing colors between tabs is a first approach but I think that is not that difficult to come up with a better one.
In your approach:
I think that in your approach what you are doing is as soon as a new page is selected you trigger a transition in the background color. In that case the transitions are fixed in time (200 milliseconds in your case) but it doesn't feel natural, is even worse when you change pages swiping between them. The problem is that the onPageSelected is a on/off trigger. You are on page 0 or 1 or 2, but there is no such state as "between 0 and 1".
Wouldn't be great if the color would be exactly proportional to the amount of swipe, this is proportional to the real state in the transition between tabs??
How to do it?
In the activity hosting the viewpager, set a layout with as many background layers as tabs you want in the view pager. If you have 3 tabs then set 3 background layers overlapping one to each other.
For example:
<LinearLayout
android:id="#+id/background_main_fragment_activity_bottom"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#drawable/background_gradient_radial_blue_vivid"
android:orientation="vertical"
tools:visibility="visible">
</LinearLayout>
<LinearLayout
android:id="#+id/background_main_fragment_activity_middle"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#drawable/background_gradient_radial_blue_samknows"
android:orientation="vertical"
tools:visibility="visible">
</LinearLayout>
<LinearLayout
android:id="#+id/background_main_fragment_activity_top"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#drawable/background_gradient_radial_blue_light"
android:orientation="vertical"
tools:visibility="visible">
</LinearLayout>
<android.support.v4.view.ViewPager
android:id="#+id/viewpager"
android:layout_width="match_parent"
android:layout_height="match_parent">
</android.support.v4.view.ViewPager>
Each LinearLayout is a background for a particular tab.
The idea is modify the alpha value of the linear layouts making them visible, partially visible or invisible.
Instead of using the onPageSelected method we are gonna use the onPageScrolled, take a look:
// Set a listener that will be invoked whenever the page changes or is incrementally scrolled.
// This listener is used for changing smoothly the colour of the background, this is modifying the visibility of the different layers
viewPager.setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener()
{
// Called when the scroll state changes
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels)
{
super.onPageScrolled(position, positionOffset, positionOffsetPixels);
switch (position)
{
case 0:
layout_ll_background_middle.setAlpha(positionOffset);
break;
case 1:
layout_ll_background_top.setAlpha(positionOffset);
break;
default:
break;
}
}
// This method will be invoked when a new page becomes selected
#Override
public void onPageSelected(int position)
{ // When swiping between pages, select the corresponding tab
getActionBar().setSelectedNavigationItem(position);
// Set the title
actionBar.setTitle(adapter_ViewPager.getPageTitle(position));
}
});
Hope it helps to make it better.
Good luck
Since timed transitions don't quite fit the usecase and alpha shouldn't be used (in that way) for transitions/animations on android here is what I came up with:
First of all be sure that no child view has a background set where it shouldn't. In your base layout set the background of the layout to your start color.
In your Activity.onCreate() add this:
final ViewPager mPager = (ViewPager) findViewById(R.id.ofYourPager);
// if you have a page indicator
final YourPageIndicator pageIndicator = (YourPageIndicator) findViewById(R.id.ofYourIndicator);
// change background on swipe
final int[] colors = {
getResources().getColor(R.color.yourFirstColor),
getResources().getColor(R.color.yourSecondColor),
getResources().getColor(R.color.yourThirdColor),
// --- add as many colours as you have pages ---
};
final ArgbEvaluator argbEvaluator = new ArgbEvaluator();
mPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
if (position < (mPagerAdapter.getCount() - 1) && position < (colors.length - 1)) {
Integer color = (Integer) argbEvaluator.evaluate(positionOffset, colors[position], colors[position + 1]);
mPager.setBackgroundColor(color);
pageIndicator.setBackgroundColor(color);
} else {
mPager.setBackgroundColor(colors[colors.length - 1]);
pageIndicator.setBackgroundColor(colors[colors.length - 1]);
}
}
#Override
public void onPageSelected(int position) {}
#Override
public void onPageScrollStateChanged(int state) {}
});
I took the idea from this post I found: http://kubaspatny.github.io/2014/09/18/viewpager-background-transition/

Android ExpandableListView using animation

I'm using
<ExpandableListView
android:id="#+id/listView"
android:layout_width="match_parent"
android:layout_height="match_parent" >
</ExpandableListView>
i want add animation slide for child when onclick parent . So How can i do ?
Final Update
It's been quite a while since I wrote this answer. Since then a lot has changed. The biggest change is with the introduction of RecyclerView that makes animating a list or grid easy. I highly recommend switching over to RecyclerViews if you can. For those who can't I will see what I can do regarding fixing the bugs for my library.
Original answer
I actually do not like the popular implementation of an animated ExpandableListView that simply uses a ListView with an expand animation because in my use case, each of my groups had a lot of children, therefore it was not feasible to use a normal ListView as the child views will not be recycled and the memory usage will be huge with poor performance. Instead, I went with a much more difficult but more scalable and flexible approach.
I extended the ExpandableListView class and overrode the onCollapse and onExpand functions, I also created a subclass of a BaseExpandableListAdapter called AnimatedExpandableListAdapter. Inside the adapter, I overrode the getChildView function and made the function final so that the function cannot be overrode again. Instead I provided another function called getRealChildView for subclasses to override to provide a real child view. I then added an animation flag to the class and made getChildView return a dummy view if the animation flag was set and the real view if the flag was not set. Now with the stage set I do the following for onExpand:
Set the animation flag in the adapter and tell the adapter which group is expanding.
Call notifyDataSetChanged() (forces the adapter to call getChildView() for all views on screen).
The adapter (in animation mode) will then create a dummy view for the expanding group that has initial height 0. The adapter will then get the real child views and pass these views to the dummy view.
The dummy view will then start to draw the real child views within it's own onDraw() function.
The adapter will kick off an animation loop that will expand the dummy view until it is of the right size. It will also set an animation listener so that it can clear the animation flag once the animation completes and will call notifyDataSetChanged() as well.
Finally with all of this done, I was able to not only get the desired animation effect but also the desired performance as this method will work with group with over 100 children.
For the collapsing animation, a little more work needs to be done to get this all setup and running. In particular, when you override onCollapse, you do not want to call the parent's function as it will collapse the group immediately leaving you no chance to play an animation. Instead you want to call super.onCollapse at the end of the collapse animation.
UPDATE:
I spent some time this weekend to rewrite my implementation of this AnimatedExpandableListView and I'm releasing the source with an example usage here:
https://github.com/idunnololz/AnimatedExpandableListView/
animateLayoutChanges adds auto-animation
<ExpandableListView
android:animateLayoutChanges="true"
android:layout_width="fill_parent"
android:layout_height="fill_parent"/>
#idunnololz solution works great. however i would like to add some code to collapse previously expanded group.
private int previousGroup=-1;
listView.setOnGroupClickListener(new OnGroupClickListener() {
#Override
public boolean onGroupClick(ExpandableListView parent, View v, int groupPosition, long id) {
// We call collapseGroupWithAnimation(int) and
// expandGroupWithAnimation(int) to animate group
// expansion/collapse.
if (listView.isGroupExpanded(groupPosition)) {
listView.collapseGroupWithAnimation(groupPosition);
previousGroup=-1;
} else {
listView.expandGroupWithAnimation(groupPosition);
if(previousGroup!=-1){
listView.collapseGroupWithAnimation(previousGroup);
}
previousGroup=groupPosition;
}
return true;
}
});
#idunnololz solution is working great, but I experienced weird behavior with my custom layout for group. The expand operation was not executed properly, the collapse however worked perfect. I imported his test project and it worked just fine, so I realized the problem is with my custom layout. However when I was not able to locate the problem after some investigation, I decided to uncomment these lines of code in his AnimatedExpandListView:
if (lastGroup && Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
return expandGroup(groupPos, true);
}
which caused the problem (my app is aimed for Android 4.0+).
Found this snnipet not remebering where here in Stack Overflow. Have two basic static methods: expand(View v) and collapse(View v).
You only have to pass the view you want to hide show.
Note: I Don't recomend pass a view having wrap_content as height. May not work fine.
public class expand {
public static void expand(View view) {
view.setVisibility(View.VISIBLE);
final int widthSpec = View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED);
final int heightSpec = View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED);
view.measure(widthSpec, heightSpec);
ValueAnimator mAnimator = slideAnimator(view, 0, view.getMeasuredHeight());
mAnimator.start();
}
public static void collapse(final View view) {
int finalHeight = view.getHeight();
ValueAnimator mAnimator = slideAnimator(view, finalHeight, 0);
mAnimator.addListener(new Animator.AnimatorListener() {
#Override
public void onAnimationEnd(Animator animator) {
view.setVisibility(View.GONE);
}
#Override
public void onAnimationStart(Animator animation) {
}
#Override
public void onAnimationCancel(Animator animation) {
}
#Override
public void onAnimationRepeat(Animator animation) {
}
});
mAnimator.start();
}
private static ValueAnimator slideAnimator(final View v, int start, int end) {
ValueAnimator animator = ValueAnimator.ofInt(start, end);
animator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
#Override
public void onAnimationUpdate(ValueAnimator valueAnimator) {
int value = (Integer) valueAnimator.getAnimatedValue();
ViewGroup.LayoutParams layoutParams = v.getLayoutParams();
layoutParams.height = value;
v.setLayoutParams(layoutParams);
}
});
return animator;
}
}

Can I partially hide a layout?

As I've a master in MS Paint, I will just upload a picture selfdescripting what I'm trying to achieve.
I've searched, but I'm not really sure what do I've to search. I've found something called Animations. I managed to rotate, fade, etc an element from a View (with this great tutorial http://www.vogella.com/articles/AndroidAnimation/article.html)
But this is a bit limited for what I'm trying to achieve, and now, I'm stuck, because I don't know how is this really called in android development. Tried words like "scrollup layouts" but I didn't get any better results.
Can you give me some tips?
Thank you.
You can see a live example, with this app: https://play.google.com/store/apps/details?id=alexcrusher.just6weeks
Sincerely,
Sergi
Use something like this as your layout (Use Linear, Relative or other layout if you wish):
<LinearLayout
android:id="#+id/lty_parent">
<LinearLayout
android:id="#+id/lyt_first" />
<LinearLayout
android:id="#+id/lyt_second"/>
</LinearLayout>
And then in an onClick method on whatever you want to use to control it, set the Visibility between Visible and Gone.
public void buttonClickListener(){
((Button) findViewById(R.id.your_button))
.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if (lyt_second.getVisibility() == View.GONE) {
lyt_second.setVisibility(View.VISIBILE);
}
else {
lyt_second.setVisibility(View.GONE);
}
});
Which is fine if you just want a simple appear/disappear with nothing fancy. Things get a little bit more complicated if you want to animate it, as you need to play around with negative margins in order to make it appear to grow and shrink, like so:
We use the same onClick method that we did before, but this time when we click it starts up a custom SlideAnimation for the hidden/visible view.
#Override
public void onClick(View v) {
SlideAnimation slideAnim = new SlideAnimation(lyt_second, time);
lyt_second.startAnimation(slideAnim);
}
The implementation of the SlideAnimation is based on a general Animation class, which we extend and then Override the transformation.
public SlideAnimation(View view, int duration) {
//Set the duration of the animation to the int we passed in
setDuration(duration);
//Set the view to be animated to the view we passed in
viewToBeAnimated = view;
//Get the Margin Parameters for the view so we can edit them
viewMarginParams = (MarginLayoutParams) view.getLayoutParams();
//If the view is VISIBLE, hide it after. If it's GONE, show it before we start.
hideAfter = (view.getVisibility() == View.VISIBLE);
//First off, start the margin at the bottom margin we've already set.
//You need your layout to have a negative margin for this to work correctly.
marginStart = viewMarginParams.bottomMargin;
//Decide if we're expanding or collapsing
if (marginStart == 0){
marginEnd = 0 - view.getHeight();
}
else {
marginEnd = 0;
}
//Make sure the view is visible for our animation
view.setVisibility(View.VISIBLE);
}
#Override
protected void applyTransformation(float interpolatedTime, Transformation t) {
super.applyTransformation(interpolatedTime, t);
if (interpolatedTime < 1.0f) {
// Setting the new bottom margin to the start of the margin
// plus the inbetween bits
viewMarginParams.bottomMargin = marginStart
+ (int) ((marginEnd - marginStart) * interpolatedTime);
// Request the layout as it happens so we can see it redrawing
viewToBeAnimated.requestLayout();
// Make sure we have finished before we mess about with the rest of it
} else if (!alreadyFinished) {
viewMarginParams.bottomMargin = marginEnd;
viewToBeAnimated.requestLayout();
if (hideAfter) {
viewToBeAnimated.setVisibility(View.GONE);
}
alreadyFinished = true;
}
hideAfter = false;
}
}
EDIT: If anyone had used this code before and found that if you click on the button that starts the animation more than once before the animation was finished, it would mess up the animation from then on, causing it to always hide the view after the animation finished. I missed the reset of the hideAfter boolean near the bottom of the code, added it now.
you can do this manually by using setvisibility feature on the event onClick()
or
use this
dynamically adding two views one below other

Adding items into listview dynamically [duplicate]

In iOS, there is a very easy and powerful facility to animate the addition and removal of UITableView rows, here's a clip from a youtube video showing the default animation. Note how the surrounding rows collapse onto the deleted row. This animation helps users keep track of what changed in a list and where in the list they were looking at when the data changed.
Since I've been developing on Android I've found no equivalent facility to animate individual rows in a TableView. Calling notifyDataSetChanged() on my Adapter causes the ListView to immediately update its content with new information. I'd like to show a simple animation of a new row pushing in or sliding out when the data changes, but I can't find any documented way to do this. It looks like LayoutAnimationController might hold a key to getting this to work, but when I set a LayoutAnimationController on my ListView (similar to ApiDemo's LayoutAnimation2) and remove elements from my adapter after the list has displayed, the elements disappear immediately instead of getting animated out.
I've also tried things like the following to animate an individual item when it is removed:
#Override
protected void onListItemClick(ListView l, View v, final int position, long id) {
Animation animation = new ScaleAnimation(1, 1, 1, 0);
animation.setDuration(100);
getListView().getChildAt(position).startAnimation(animation);
l.postDelayed(new Runnable() {
public void run() {
mStringList.remove(position);
mAdapter.notifyDataSetChanged();
}
}, 100);
}
However, the rows surrounding the animated row don't move position until they jump to their new positions when notifyDataSetChanged() is called. It appears ListView doesn't update its layout once its elements have been placed.
While writing my own implementation/fork of ListView has crossed my mind, this seems like something that shouldn't be so difficult.
Thanks!
Animation anim = AnimationUtils.loadAnimation(
GoTransitApp.this, android.R.anim.slide_out_right
);
anim.setDuration(500);
listView.getChildAt(index).startAnimation(anim );
new Handler().postDelayed(new Runnable() {
public void run() {
FavouritesManager.getInstance().remove(
FavouritesManager.getInstance().getTripManagerAtIndex(index)
);
populateList();
adapter.notifyDataSetChanged();
}
}, anim.getDuration());
for top-to-down animation use :
<set xmlns:android="http://schemas.android.com/apk/res/android">
<translate android:fromYDelta="20%p" android:toYDelta="-20"
android:duration="#android:integer/config_mediumAnimTime"/>
<alpha android:fromAlpha="0.0" android:toAlpha="1.0"
android:duration="#android:integer/config_mediumAnimTime" />
</set>
The RecyclerView takes care of adding, removing, and re-ordering animations!
This simple AndroidStudio project features a RecyclerView. take a look at the commits:
commit of the classic Hello World Android app
commit, adding a RecyclerView to the project (content not dynamic)
commit, adding functionality to modify content of RecyclerView at runtime (but no animations)
and finally...commit adding animations to the RecyclerView
Take a look at the Google solution. Here is a deletion method only.
ListViewRemovalAnimation project code and Video demonstration
It needs Android 4.1+ (API 16). But we have 2014 outside.
Since ListViews are highly optimized i think this is not possible to accieve. Have you tried to create your "ListView" by code (ie by inflating your rows from xml and appending them to a LinearLayout) and animate them?
Have you considered animating a sweep to the right? You could do something like drawing a progressively larger white bar across the top of the list item, then removing it from the list. The other cells would still jerk into place, but it'd better than nothing.
call
listView.scheduleLayoutAnimation();
before changing the list
I hacked together another way to do it without having to manipulate list view. Unfortunately, regular Android Animations seem to manipulate the contents of the row, but are ineffectual at actually shrinking the view. So, first consider this handler:
private Handler handler = new Handler() {
#Override
public void handleMessage(Message message) {
Bundle bundle = message.getData();
View view = listView.getChildAt(bundle.getInt("viewPosition") -
listView.getFirstVisiblePosition());
int heightToSet;
if(!bundle.containsKey("viewHeight")) {
Rect rect = new Rect();
view.getDrawingRect(rect);
heightToSet = rect.height() - 1;
} else {
heightToSet = bundle.getInt("viewHeight");
}
setViewHeight(view, heightToSet);
if(heightToSet == 1)
return;
Message nextMessage = obtainMessage();
bundle.putInt("viewHeight", (heightToSet - 5 > 0) ? heightToSet - 5 : 1);
nextMessage.setData(bundle);
sendMessage(nextMessage);
}
Add this collection to your List adapter:
private Collection<Integer> disabledViews = new ArrayList<Integer>();
and add
public boolean isEnabled(int position) {
return !disabledViews.contains(position);
}
Next, wherever it is that you want to hide a row, add this:
Message message = handler.obtainMessage();
Bundle bundle = new Bundle();
bundle.putInt("viewPosition", listView.getPositionForView(view));
message.setData(bundle);
handler.sendMessage(message);
disabledViews.add(listView.getPositionForView(view));
That's it! You can change the speed of the animation by altering the number of pixels that it shrinks the height at once. Not real sophisticated, but it works!
After inserting new row to ListView, I just scroll the ListView to new position.
ListView.smoothScrollToPosition(position);
I haven't tried it but it looks like animateLayoutChanges should do what you're looking for. I see it in the ImageSwitcher class, I assume it's in the ViewSwitcher class as well?
Since Android is open source, you don't actually need to reimplement ListView's optimizations. You can grab ListView's code and try to find a way to hack in the animation, you can also open a feature request in android bug tracker (and if you decided to implement it, don't forget to contribute a patch).
FYI, the ListView source code is here.
Here's the source code to let you delete rows and reorder them.
A demo APK file is also available. Deleting rows is done more along the lines of Google's Gmail app that reveals a bottom view after swiping a top view. The bottom view can have an Undo button or whatever you want.
As i had explained my approach in my site i shared the link.Anyways the idea is create bitmaps
by getdrawingcache .have two bitmap and animate the lower bitmap to create the moving effect
Please see the following code:
listView.setOnItemClickListener(new AdapterView.OnItemClickListener()
{
public void onItemClick(AdapterView<?> parent, View rowView, int positon, long id)
{
listView.setDrawingCacheEnabled(true);
//listView.buildDrawingCache(true);
bitmap = listView.getDrawingCache();
myBitmap1 = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), rowView.getBottom());
myBitmap2 = Bitmap.createBitmap(bitmap, 0, rowView.getBottom(), bitmap.getWidth(), bitmap.getHeight() - myBitmap1.getHeight());
listView.setDrawingCacheEnabled(false);
imgView1.setBackgroundDrawable(new BitmapDrawable(getResources(), myBitmap1));
imgView2.setBackgroundDrawable(new BitmapDrawable(getResources(), myBitmap2));
imgView1.setVisibility(View.VISIBLE);
imgView2.setVisibility(View.VISIBLE);
RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
lp.setMargins(0, rowView.getBottom(), 0, 0);
imgView2.setLayoutParams(lp);
TranslateAnimation transanim = new TranslateAnimation(0, 0, 0, -rowView.getHeight());
transanim.setDuration(400);
transanim.setAnimationListener(new Animation.AnimationListener()
{
public void onAnimationStart(Animation animation)
{
}
public void onAnimationRepeat(Animation animation)
{
}
public void onAnimationEnd(Animation animation)
{
imgView1.setVisibility(View.GONE);
imgView2.setVisibility(View.GONE);
}
});
array.remove(positon);
adapter.notifyDataSetChanged();
imgView2.startAnimation(transanim);
}
});
For understanding with images see this
Thanks.
I have done something similar to this. One approach is to interpolate over the animation time the height of the view over time inside the rows onMeasure while issuing requestLayout() for the listView. Yes it may be be better to do inside the listView code directly but it was a quick solution (that looked good!)
Just sharing another approach:
First set the list view's android:animateLayoutChanges to true:
<ListView
android:id="#+id/items_list"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:animateLayoutChanges="true"/>
Then I use a handler to add items and update the listview with delay:
Handler mHandler = new Handler();
//delay in milliseconds
private int mInitialDelay = 1000;
private final int DELAY_OFFSET = 1000;
public void addItem(final Integer item) {
mHandler.postDelayed(new Runnable() {
#Override
public void run() {
new Thread(new Runnable() {
#Override
public void run() {
mDataSet.add(item);
runOnUiThread(new Runnable() {
#Override
public void run() {
mAdapter.notifyDataSetChanged();
}
});
}
}).start();
}
}, mInitialDelay);
mInitialDelay += DELAY_OFFSET;
}

Categories

Resources