Adding animation to a List View in Android

2019-02-12 15:53发布

问题:

I want to animate the items of the list view. At Present i am applying the Transition Animation on the list items whenever new items are added. But this is not the animation i want to achieve. I want that when a new item is added in the list view at that time the whole List view move a place down to make way for the newly added item.

Currently the code i am using is :

set = new AnimationSet(true);

    animation = new AlphaAnimation(0.0f, 1.0f);
    animation.setDuration(50);
    set.addAnimation(animation);

    animation = new TranslateAnimation(
        Animation.RELATIVE_TO_SELF, 0.0f,Animation.RELATIVE_TO_SELF, 0.0f,
        Animation.RELATIVE_TO_SELF, -1.0f,Animation.RELATIVE_TO_SELF, 0.0f
    );
    animation.setDuration(150);
    set.addAnimation(animation);

    LayoutAnimationController controller = new LayoutAnimationController(set, 1.0f);
    l.setLayoutAnimation(controller);
    l.setAdapter(listAdaptor);

And then while adding items through button onClick

    l.startLayoutAnimation();

Any other suggestions to achieve such animation.

回答1:

I got the Solution to this. I animate each added element in the getView method of my Custom Adapter.

public View getView(int position, View convertView, ViewGroup parent) {

        View v = convertView;

        if (v == null) {
            LayoutInflater vi = (LayoutInflater) getActivity()
                    .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            v = vi.inflate(R.layout.simple_list_item_1, null);
        }

        ListData o = list.get(position);
        TextView tt = (TextView) v.findViewById(R.id.toptext);

        tt.setText(o.content);

        Log.d("ListTest", "Position : "+position);
       if(flag == false) {
        Animation animation = AnimationUtils.loadAnimation(getActivity(), R.anim.slide_top_to_bottom);
        v.startAnimation(animation);}
        return v;
    }

And thereby achieved the animation as i had stated for.