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.

example:

LayoutTransition transition = new LayoutTransition();
container.setLayoutTransition(transition);


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


Modify MainActivity.java 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.app.Activity;
import android.content.Context;

public class MainActivity extends Activity {

EditText textIn;
Button buttonAdd;
LinearLayout container;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textIn = (EditText)findViewById(R.id.textin);
buttonAdd = (Button)findViewById(R.id.add);
container = (LinearLayout)findViewById(R.id.container);

buttonAdd.setOnClickListener(new OnClickListener(){

@Override
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(R.id.textout);
textOut.setText(textIn.getText().toString());
Button buttonRemove = (Button)addView.findViewById(R.id.remove);
buttonRemove.setOnClickListener(new OnClickListener(){

@Override
public void onClick(View v) {
((LinearLayout)addView.getParent()).removeView(addView);
}});

container.addView(addView, 0);
}});

LayoutTransition transition = new LayoutTransition();
container.setLayoutTransition(transition);

}

}


download filesDownload the files.

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

No comments:

Post a Comment