星期四, 八月 21, 2014

Button 实现淡入淡出动画

布局文件:
activity_main.xml:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.example.buttonana.MainActivity" >
  <Button
      android:layout_marginTop="50dp"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"     
      android:id="@+id/animationid"
      android:text="fade out"/>

  <Button
      android:id="@+id/mainbtn"
      android:layout_width="match_parent"
      android:layout_height="wrap_content"
      android:layout_alignLeft="@+id/animationid"
      android:layout_alignParentTop="true"
      android:layout_marginTop="170dp"
      android:text="Click Me" />

</RelativeLayout>

关键语句:
      amt.setFillAfter(true);//important.

package com.example.buttonana;

import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.animation.AlphaAnimation;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.Button;

public class MainActivity extends Activity {

    Button mainbtn;
    Button animationbtn;
   
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mainbtn=(Button)this.findViewById(R.id.mainbtn);
        animationbtn=(Button)this.findViewById(R.id.animationid);
        mainbtn.setOnClickListener(new View.OnClickListener() {
           
            @Override
            public void onClick(View v) {
                Log.d("BUTTON","enter.........................................................");
                Animation t =getAnimation();
                animationbtn.clearAnimation();
                animationbtn.setAnimation(t);
                t.startNow();
            }
        });
       
    }
  public Animation getAnimation()
  {
      Animation amt=new AlphaAnimation(1.0f,0.01f);
      amt.setDuration(4*1000);
      amt.setFillAfter(true);//important.
      return amt;
     
  }

}