Monday, May 20, 2013

Apply animations on layout changes using LayoutTransition

LayoutTransition (Added in API level 11) enables automatic animations on layout changes in ViewGroup objects.


LayoutTransition transition = new LayoutTransition();

It's the default animations effect apply on the dynamic view in last exercise "Add and Remove view dynamically".

Modify from last exercise.
- Apply LayoutTransition on container of LinearLayout.
- To made the effect noticeable, insert dynamic view in front by calling container.addView(addView, 0) instead of container.addView(addView).
- Modify AndroidManifest.xml to have minSdkVersion="11".

package com.example.androiddynamicview;

import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.animation.LayoutTransition;
import android.content.Context;

public class MainActivity extends Activity {

EditText textIn;
Button buttonAdd;
LinearLayout container;

protected void onCreate(Bundle savedInstanceState) {
textIn = (EditText)findViewById(;
buttonAdd = (Button)findViewById(;
container = (LinearLayout)findViewById(;

buttonAdd.setOnClickListener(new OnClickListener(){

public void onClick(View arg0) {
LayoutInflater layoutInflater =
(LayoutInflater) getBaseContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
final View addView = layoutInflater.inflate(R.layout.row, null);
TextView textOut = (TextView)addView.findViewById(;
Button buttonRemove = (Button)addView.findViewById(;
buttonRemove.setOnClickListener(new OnClickListener(){

public void onClick(View v) {

container.addView(addView, 0);

LayoutTransition transition = new LayoutTransition();



download filesDownload the files.

To apply Android 3.0 animation API on old devices, NineOldAndroids is an alternative.

No comments:

Post a Comment