Create fade in fade out and slide animation for a View

Description

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;
//ww w. j  av a2  s . c om
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);
        }
    }
}
Create fade in fade out and slide animation for a View




















Home »
  Android »
    Android UI »




UI Basics
Action Bar
Animation
Button
Canvas
CheckBox
Clock Date Picker
Dialog
EditText
Event
Fragment
Gesture
GridView
ImageView
Layout
ListView
Map
Menu
Model
OpenGL
ProgressBar
RadioButton
Spinner
Tab
TextView
Thread
Toast
Video
View
WebView