Android UI How to - Create fade in fade out and slide animation for a View








The following code shows how to Create fade in fade out and slide animation for a View.

Example

Main layout xml file

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
  android:orientation="vertical"
  android:layout_width="fill_parent"
  android:layout_height="fill_parent">
  <Button
    android:id="@+id/toggleButton"
    android:layout_width="fill_parent" 
    android:layout_height="wrap_content" 
    android:text="Click to Toggle"
  />
  <View
    android:id="@+id/theView"
    android:layout_width="fill_parent" 
    android:layout_height="wrap_content" 
    android:background="#AAA"
  />
</LinearLayout>

Main Activity Java code

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
/*from   w w w .  ja  v  a  2s  .c o  m*/
public class MainActivity extends Activity implements View.OnClickListener {

    View viewToAnimate;
    
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        
        Button button = (Button)findViewById(R.id.toggleButton);
        button.setOnClickListener(this);
        
        viewToAnimate = findViewById(R.id.theView);
    }
    
    @Override
    public void onClick(View v) {
        if(viewToAnimate.getAlpha() > 0f) {
            //slide it out to the right
            viewToAnimate.animate().alpha(0f).translationX(500f);
        } else {
            //do a fade-in in-place
            viewToAnimate.setTranslationX(0f);
            viewToAnimate.animate().alpha(1f);
        }
    }
}
null