Thursday, May 22, 2014

Code Examples of TranslateAnimation

An animation that controls the position of an object. See th android.view.animation description for details and sample code.
  • android.view.animation.TranslateAnimation

/*
 * Copyright (C) 2010 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
 
package com.replica.replicaisland;
 
import java.lang.reflect.InvocationTargetException;
 
import android.app.Activity;
import android.content.Intent;
import android.graphics.drawable.AnimationDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.DisplayMetrics;
import android.view.MotionEvent;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.view.animation.TranslateAnimation;
import android.widget.ImageView;
 
public class AnimationPlayerActivity extends Activity {
    public static final int KYLE_DEATH = 0;
    public static final int WANDA_ENDING = 1;
    public static final int KABOCHA_ENDING = 2;
    public static final int ROKUDOU_ENDING = 3;
     
    private AnimationDrawable mAnimation;
    private int mAnimationType;
    private long mAnimationEndTime;
     
    private KillActivityHandler mKillActivityHandler = new KillActivityHandler();
 
    class KillActivityHandler extends Handler {
 
        @Override
        public void handleMessage(Message msg) {
            AnimationPlayerActivity.this.finish();
            if (UIConstants.mOverridePendingTransition != null) {
               try {
                  UIConstants.mOverridePendingTransition.invoke(AnimationPlayerActivity.this, R.anim.activity_fade_in, R.anim.activity_fade_out);
               } catch (InvocationTargetException ite) {
                   DebugLog.d("Activity Transition", "Invocation Target Exception");
               } catch (IllegalAccessException ie) {
                   DebugLog.d("Activity Transition", "Illegal Access Exception");
               }
            }
        }
 
        public void sleep(long delayMillis) {
            this.removeMessages(0);
            sendMessageDelayed(obtainMessage(0), delayMillis);
        }
    };
     
    @Override
    public void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
           
      final Intent callingIntent = getIntent();
      mAnimationType = callingIntent.getIntExtra("animation", KYLE_DEATH);
       
      if (mAnimationType == KYLE_DEATH) {
          setContentView(R.layout.animation_player);
     
          ImageView canvasImage = (ImageView) findViewById(R.id.animation_canvas);
          canvasImage.setImageResource(R.anim.kyle_fall);
          mAnimation = (AnimationDrawable) canvasImage.getDrawable();
      } else {

          if (mAnimationType == WANDA_ENDING || mAnimationType == KABOCHA_ENDING) {
              float startX = 0.0f;
              DisplayMetrics metrics = new DisplayMetrics();
              getWindowManager().getDefaultDisplay().getMetrics(metrics);
              if (mAnimationType == WANDA_ENDING) {
                  setContentView(R.layout.good_ending_animation);
                  startX = 200 * metrics.density;
                  
              } else {
                  setContentView(R.layout.kabocha_ending_animation);
                  startX = -200 * metrics.density;
              }
               
              // HACK
              // the TranslateAnimation system doesn't support device independent pixels.
              // So for the Wanda ending and Kabocha endings, in which the game over text
              // scrolls in horizontally, compute the size based on the actual density of
              // the display and just generate the anim in code.  The Rokudou animation
              // can be safely loaded from a file.
              Animation gameOverAnim = new TranslateAnimation(startX, 0, 0, 0);
              gameOverAnim.setDuration(6000);
              gameOverAnim.setFillAfter(true);
              gameOverAnim.setFillEnabled(true);
              gameOverAnim.setStartOffset(8000);
               
              View background = findViewById(R.id.animation_background);
              View foreground = findViewById(R.id.animation_foreground);
              View gameOver = findViewById(R.id.game_over);
 
              Animation foregroundAnim = AnimationUtils.loadAnimation(this, R.anim.horizontal_layer2_slide);
              Animation backgroundAnim = AnimationUtils.loadAnimation(this, R.anim.horizontal_layer1_slide);
               
              background.startAnimation(backgroundAnim);
              foreground.startAnimation(foregroundAnim);
              gameOver.startAnimation(gameOverAnim);
               
              mAnimationEndTime = gameOverAnim.getDuration() + System.currentTimeMillis();
          } else if (mAnimationType == ROKUDOU_ENDING) {
              setContentView(R.layout.rokudou_ending_animation);
              View background = findViewById(R.id.animation_background);
              View sphere = findViewById(R.id.animation_sphere);
              View cliffs = findViewById(R.id.animation_cliffs);
              View rokudou = findViewById(R.id.animation_rokudou);
              View gameOver = findViewById(R.id.game_over);
 
               
              Animation backgroundAnim = AnimationUtils.loadAnimation(this, R.anim.rokudou_slide_bg);
              Animation sphereAnim = AnimationUtils.loadAnimation(this, R.anim.rokudou_slide_sphere);
              Animation cliffsAnim = AnimationUtils.loadAnimation(this, R.anim.rokudou_slide_cliffs);
              Animation rokudouAnim = AnimationUtils.loadAnimation(this, R.anim.rokudou_slide_rokudou);
              Animation gameOverAnim = AnimationUtils.loadAnimation(this, R.anim.rokudou_game_over);
 
              background.startAnimation(backgroundAnim);
              sphere.startAnimation(sphereAnim);
              cliffs.startAnimation(cliffsAnim);
              rokudou.startAnimation(rokudouAnim);
              gameOver.startAnimation(gameOverAnim);
              mAnimationEndTime = gameOverAnim.getDuration() + System.currentTimeMillis();
          } else {
              assert false;
          }
      }
       
      // Pass the calling intent back so that we can figure out which animation just played.
      setResult(RESULT_OK, callingIntent);
       
    }
     
    @Override
    public boolean onTouchEvent(MotionEvent event) {
        long time = System.currentTimeMillis();
        if (time > mAnimationEndTime) {
            finish();
        } else {
            try {
                Thread.sleep(32);
            } catch (InterruptedException e) {
                // Safe to ignore.
            }
        }
        return true;
    }
 
    @Override
    public void onWindowFocusChanged(boolean hasFocus) {
      if (hasFocus && mAnimation != null) {
          mAnimation.start();
          mKillActivityHandler.sleep(mAnimation.getDuration(0) * mAnimation.getNumberOfFrames());
      }
    }
}
/*
 * Copyright (C) 2009 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
 
package com.example.android.apis.view;
 
// Need the following import to get access to the app resources, since this
// class is in a sub-package.
import com.example.android.apis.R;
 
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.animation.AnimationUtils;
import android.view.animation.Animation;
import android.view.animation.TranslateAnimation;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Spinner;
 
public class Animation3 extends Activity implements AdapterView.OnItemSelectedListener {
    private static final String[] INTERPOLATORS = {
            "Accelerate", "Decelerate", "Accelerate/Decelerate",
            "Anticipate", "Overshoot", "Anticipate/Overshoot",
            "Bounce"
    };
 
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.animation_3);
 
        Spinner s = (Spinner) findViewById(R.id.spinner);
        ArrayAdapter adapter = new ArrayAdapter(this,
                android.R.layout.simple_spinner_item, INTERPOLATORS);
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        s.setAdapter(adapter);
        s.setOnItemSelectedListener(this);
    }
 
    public void onItemSelected(AdapterView parent, View v, int position, long id) {
        final View target = findViewById(R.id.target);
        final View targetParent = (View) target.getParent();
 
        Animation a = new TranslateAnimation(0.0f,
                targetParent.getWidth() - target.getWidth() - targetParent.getPaddingLeft() -
                targetParent.getPaddingRight(), 0.0f, 0.0f);
        a.setDuration(1000);
        a.setStartOffset(300);
        a.setRepeatMode(Animation.RESTART);
        a.setRepeatCount(Animation.INFINITE);
 
        switch (position) {
            case 0:
                a.setInterpolator(AnimationUtils.loadInterpolator(this,
                        android.R.anim.accelerate_interpolator));
                break;
            case 1:
                a.setInterpolator(AnimationUtils.loadInterpolator(this,
                        android.R.anim.decelerate_interpolator));
                break;
            case 2:
                a.setInterpolator(AnimationUtils.loadInterpolator(this,
                        android.R.anim.accelerate_decelerate_interpolator));
                break;
            case 3:
                a.setInterpolator(AnimationUtils.loadInterpolator(this,
                        android.R.anim.anticipate_interpolator));
                break;
            case 4:
                a.setInterpolator(AnimationUtils.loadInterpolator(this,
                        android.R.anim.overshoot_interpolator));
                break;
            case 5:
                a.setInterpolator(AnimationUtils.loadInterpolator(this,
                        android.R.anim.anticipate_overshoot_interpolator));
                break;
            case 6:
                a.setInterpolator(AnimationUtils.loadInterpolator(this,
                        android.R.anim.bounce_interpolator));
                break;
        }
 
        target.startAnimation(a);
    }
 
    public void onNothingSelected(AdapterView parent) {
    }
}
/*
 * Copyright (C) 2011 The LiteListen Project
 * 
 * Licensed under the Mozilla Public Licence, version 1.1 (the "License");
 * You may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.mozilla.org/MPL/MPL-1.1.html
 * 
 * ???????????????? ??????? 2011
 * ???? Mozilla Public Licence 1.1 ??????????????B????
 * ????????????????????????????
 * ???????????????????????????
 *
 *      http://www.mozilla.org/MPL/MPL-1.1.html
 */
 
package com.galapk.litelisten;
 
import android.content.SharedPreferences.Editor;
import android.graphics.Color;
import android.util.DisplayMetrics;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.WindowManager;
import android.view.animation.Animation;
import android.view.animation.TranslateAnimation;
import android.widget.AbsoluteLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
 
@SuppressWarnings("deprecation")
public class FloatLRC extends LinearLayout
{
    // ???????????View??????
    private float DownPosX = 0;
    private float DownPosY = 0;
 
    // ?????????????????????
    private float x = 0;
    private float y = 0;
 
    private WindowManager wm;
    private WindowManager.LayoutParams layWM;
    private scrMain main;
    private DisplayMetrics dm;
 
    // ???????
    ImageView imgIcon;
    AbsoluteLayout layMain;
    TextView txtLRC1;
    TextView txtLRC2;
 
    public FloatLRC(scrMain main)
    {
        super(main);
        wm = (WindowManager) main.getApplicationContext().getSystemService("window");
        layWM = main.getLayWM();
        this.main = main;
        dm = new DisplayMetrics();
 
        // ??????????
        imgIcon = new ImageView(main);
        LinearLayout.LayoutParams layIcon = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
        layIcon.gravity = Gravity.CENTER_VERTICAL;
        imgIcon.setLayoutParams(layIcon);
 
        // ??????
        layMain = new AbsoluteLayout(main);
        LinearLayout.LayoutParams layMainPars = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.FILL_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
        layMain.setLayoutParams(layMainPars);
 
        // ???????
        txtLRC1 = new TextView(main);
        AbsoluteLayout.LayoutParams layText1 = new AbsoluteLayout.LayoutParams(AbsoluteLayout.LayoutParams.WRAP_CONTENT, AbsoluteLayout.LayoutParams.WRAP_CONTENT, 5, 0);
        txtLRC1.setLayoutParams(layText1);
        txtLRC1.setTextSize(22);
        txtLRC1.setTextColor(Color.WHITE);
        txtLRC1.setShadowLayer(1, 1, 1, Color.BLACK);
        txtLRC1.setSingleLine(true);
 
        // ???????
        txtLRC2 = new TextView(main);
        AbsoluteLayout.LayoutParams layText2 = new AbsoluteLayout.LayoutParams(AbsoluteLayout.LayoutParams.WRAP_CONTENT, AbsoluteLayout.LayoutParams.WRAP_CONTENT, 5, 35);
        txtLRC2.setLayoutParams(layText2);
        txtLRC2.setTextSize(22);
        txtLRC2.setTextColor(Color.WHITE);
        txtLRC2.setShadowLayer(1, 1, 1, Color.BLACK);
        txtLRC2.setSingleLine(true);
 
        // ??View?????????
        layMain.addView(txtLRC1);
        layMain.addView(txtLRC2);
        addView(imgIcon);
        addView(layMain);
    }
 
    /* ?????????? */
    public void SetLRC(int IconResource, String Sentence1, int Color1, String Sentence2, int Color2, Long TimeGap, int ChangedLineNumber)
    {
        main.getWindowManager().getDefaultDisplay().getMetrics(dm);
 
        if (ChangedLineNumber == 1)
        {
            Animation anim = null;
            AbsoluteLayout.LayoutParams layText2 = (AbsoluteLayout.LayoutParams) txtLRC2.getLayoutParams();
            float FontWidth = Common.GetTextWidth(Sentence2, txtLRC2.getTextSize());
 
            layWM.width = dm.widthPixels;
            layText2.x = (int) (dm.widthPixels - 75 - FontWidth);
            if (FontWidth > dm.widthPixels - 80)
                anim = new TranslateAnimation(FontWidth - (dm.widthPixels - 80), 0, 0, 0);
 
            AbsoluteLayout.LayoutParams layText1 = (AbsoluteLayout.LayoutParams) txtLRC1.getLayoutParams();
            layText1.x = 5;
            layText1.width = (int) Common.GetTextWidth(Sentence1, txtLRC1.getTextSize());
            txtLRC1.setLayoutParams(layText1);
            layText2.width = (int) FontWidth;
            txtLRC2.setLayoutParams(layText2);
 
            if (anim != null && TimeGap != null)
            {
                anim.setStartOffset((long) (TimeGap * 0.15));
                anim.setDuration((long) (TimeGap * 0.75));
                txtLRC2.startAnimation(anim);
            }
        }
        else
        {
            Animation anim = null;
            AbsoluteLayout.LayoutParams layText1 = (AbsoluteLayout.LayoutParams) txtLRC1.getLayoutParams();
            AbsoluteLayout.LayoutParams layText2 = (AbsoluteLayout.LayoutParams) txtLRC2.getLayoutParams();
            float FontWidth1 = Common.GetTextWidth(Sentence1, txtLRC1.getTextSize());
            float FontWidth2 = Common.GetTextWidth(Sentence2, txtLRC2.getTextSize());
 
            layWM.width = dm.widthPixels;
            if (FontWidth2 > dm.widthPixels - 80)
                layText2.x = 5;
            else
                layText2.x = (int) (dm.widthPixels - 75 - FontWidth2);
 
            if (FontWidth1 > dm.widthPixels - 80)
            {
                layText1.x = (int) (dm.widthPixels - 75 - FontWidth1);
                anim = new TranslateAnimation(FontWidth1 - (dm.widthPixels - 80), 0, 0, 0);
            }
            else
                layText1.x = 5;
 
            txtLRC1.setLayoutParams(layText1);
            layText2.width = (int) Common.GetTextWidth(Sentence2, txtLRC1.getTextSize());
            txtLRC2.setLayoutParams(layText2);
 
            if (anim != null && TimeGap != null)
            {
                anim.setStartOffset((long) (TimeGap * 0.15));
                anim.setDuration((long) (TimeGap * 0.75));
                txtLRC1.startAnimation(anim);
            }
        }
 
        wm.updateViewLayout(main.getFl(), layWM);
        imgIcon.setImageResource(IconResource);
        txtLRC1.setText(Sentence1);
        txtLRC1.setTextColor(Color1);
        txtLRC2.setText(Sentence2);
        txtLRC2.setTextColor(Color2);
    }
 
    @Override
    public boolean onTouchEvent(MotionEvent event)
    {
        x = event.getRawX();
        y = event.getRawY() - 25;
 
        switch (event.getAction())
        {
            case MotionEvent.ACTION_DOWN:
                DownPosX = event.getX();
                DownPosY = event.getY();
 
                break;
            case MotionEvent.ACTION_MOVE:
                MoveView();
                break;
 
            case MotionEvent.ACTION_UP:
                MoveView();
                DownPosX = 0;
                DownPosY = 0;
 
                // ??????????????????
                Editor edt = main.getSp().edit();
                edt.putInt("FloatLRCPos", layWM.y);
                main.getSt().setFloatLRCPos(layWM.y);
                edt.commit();
 
                break;
        }
        return true;
    }
 
    /* ???????????? */
    private void MoveView()
    {
        layWM.x = (int) (x - DownPosX);
        layWM.y = (int) (y - DownPosY);
        wm.updateViewLayout(this, layWM);
    }
 
    public float getDownPosX()
    {
        return DownPosX;
    }
 
    public void setDownPosX(float downPosX)
    {
        DownPosX = downPosX;
    }
 
    public float getDownPosY()
    {
        return DownPosY;
    }
 
    public void setDownPosY(float downPosY)
    {
        DownPosY = downPosY;
    }
 
    public float getX()
    {
        return x;
    }
 
    public void setX(float x)
    {
        this.x = x;
    }
 
    public float getY()
    {
        return y;
    }
 
    public void setY(float y)
    {
        this.y = y;
    }
 
    public WindowManager getWm()
    {
        return wm;
    }
 
    public void setWm(WindowManager wm)
    {
        this.wm = wm;
    }
 
    public WindowManager.LayoutParams getLayWM()
    {
        return layWM;
    }
 
    public void setLayWM(WindowManager.LayoutParams layWM)
    {
        this.layWM = layWM;
    }
 
    public scrMain getMain()
    {
        return main;
    }
 
    public void setMain(scrMain main)
    {
        this.main = main;
    }
 
    public ImageView getImgIcon()
    {
        return imgIcon;
    }
 
    public void setImgIcon(ImageView imgIcon)
    {
        this.imgIcon = imgIcon;
    }
 
    public AbsoluteLayout getLayMain()
    {
        return layMain;
    }
 
    public void setLayMain(AbsoluteLayout layMain)
    {
        this.layMain = layMain;
    }
 
    public TextView getTxtLRC1()
    {
        return txtLRC1;
    }
 
    public void setTxtLRC1(TextView txtLRC1)
    {
        this.txtLRC1 = txtLRC1;
    }
 
    public TextView getTxtLRC2()
    {
        return txtLRC2;
    }
 
    public void setTxtLRC2(TextView txtLRC2)
    {
        this.txtLRC2 = txtLRC2;
    }
}
/*
 * Copyright (C) 2011 The LiteListen Project
 * 
 * Licensed under the Mozilla Public Licence, version 1.1 (the "License");
 * You may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.mozilla.org/MPL/MPL-1.1.html
 * 
 * ???????????????? ??????? 2011
 * ???? Mozilla Public Licence 1.1 ??????????????B????
 * ????????????????????????????
 * ???????????????????????????
 *
 *      http://www.mozilla.org/MPL/MPL-1.1.html
 */

package com.galapk.litelisten;

import java.util.List;
import java.util.Map;

import android.graphics.Color;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.view.animation.Animation;
import android.view.animation.LinearInterpolator;
import android.view.animation.TranslateAnimation;
import android.widget.BaseAdapter;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

public class MusicAdapter extends BaseAdapter
{
 private scrMain main;
 private List> lstSong; // ????

 public MusicAdapter(scrMain main, List> lstSong)
 {
  this.main = main;
  this.lstSong = lstSong;
 }

 public int getCount()
 {
  return lstSong.size();
 }

 public Object getItem(int arg0)
 {
  return arg0;
 }

 public long getItemId(int position)
 {
  return position;
 }

 public View getView(int position, View convertView, ViewGroup parent)
 {
  if (position < 0 || lstSong.size() <= 0 || position >= lstSong.size())
   return null;

  if (convertView == null)
   convertView = LayoutInflater.from(main).inflate(R.layout.list_music, null);

  RelativeLayout layMusicList = (RelativeLayout) convertView.findViewById(R.id.layMusicList);
  ImageView imgAlbum = (ImageView) convertView.findViewById(R.id.imgAlbum);
  TextView txtSongTitle = (TextView) convertView.findViewById(R.id.txtSongTitle);
  TextView txtSongInfo = (TextView) convertView.findViewById(R.id.txtSongInfo);
  ImageButton btnListPlay = (ImageButton) convertView.findViewById(R.id.btnListPlay);

  txtSongTitle.setText((String) lstSong.get(position).get("Title"));
  txtSongInfo.setText((String) lstSong.get(position).get("SongInfo"));

  if (main.getMs().getPlayerStatus() == MusicService.STATUS_PLAY && main.getMs().getCurrIndex() == position)
  {
   imgAlbum.setBackgroundResource(R.drawable.album_playing);
   txtSongTitle.setTextColor(Color.parseColor("#FF9900"));
   txtSongTitle.setTextSize(Float.parseFloat(main.getSt().getListFontSize()));
   if (main.getSt().getListFontShadow())
    txtSongTitle.setShadowLayer(0.5f, 0.5f, 1, Color.parseColor("#000000"));
  }
  else if (main.getMs().getPlayerStatus() == MusicService.STATUS_PAUSE && main.getMs().getCurrIndex() == position)
  {
   imgAlbum.setBackgroundResource(R.drawable.album_paused);
   txtSongTitle.setTextColor(Color.parseColor("#FF9900"));
   txtSongTitle.setTextSize(Float.parseFloat(main.getSt().getListFontSize()));
   if (main.getSt().getListFontShadow())
    txtSongTitle.setShadowLayer(0.5f, 0.5f, 1, Color.parseColor("#000000"));
  }
  else
  {
   imgAlbum.setBackgroundResource(R.drawable.album_normal);
   txtSongTitle.setTextColor(Color.parseColor(main.getSt().getListFontColor()));
   txtSongTitle.setTextSize(Float.parseFloat(main.getSt().getListFontSize()));
   if (main.getSt().getListFontShadow())
    txtSongTitle.setShadowLayer(0.5f, 0.5f, 1, Color.parseColor(main.getSt().getListFontShadowColor()));
  }

  if (main.getSelectedItemIndex() != position)
  {
   layMusicList.setBackgroundResource(R.drawable.bg_list_music_height);
   btnListPlay.setVisibility(View.GONE);
   txtSongTitle.clearAnimation();
   txtSongInfo.clearAnimation();
  }
  else
  {
   imgAlbum.setBackgroundResource(R.drawable.album_selected);
   btnListPlay.setVisibility(View.VISIBLE);
   btnListPlay.setFocusable(false);
   btnListPlay.setFocusableInTouchMode(false);

   // ??????????????????
   float CurrWidth = Common.GetTextWidth(txtSongTitle.getText().toString(), txtSongTitle.getTextSize());
   if (CurrWidth > main.getDm().widthPixels - 165)
   {
    LinearLayout.LayoutParams laySongTitle = (LinearLayout.LayoutParams) txtSongTitle.getLayoutParams();
    laySongTitle.width = (int) CurrWidth;
    txtSongTitle.setLayoutParams(laySongTitle);

    Animation anim = new TranslateAnimation(0, -(CurrWidth - main.getDm().widthPixels + 165), 0, 0);
    anim.setDuration((long) (CurrWidth * 15));
    anim.setStartOffset(2500);
    anim.setRepeatCount(100);
    anim.setInterpolator(new LinearInterpolator());
    anim.setRepeatMode(Animation.REVERSE);
    txtSongTitle.startAnimation(anim);
   }

   // ????????????????????
   CurrWidth = Common.GetTextWidth(txtSongInfo.getText().toString(), txtSongInfo.getTextSize());
   if (CurrWidth > main.getDm().widthPixels - 165)
   {
    LinearLayout.LayoutParams laySongInfo = (LinearLayout.LayoutParams) txtSongInfo.getLayoutParams();
    laySongInfo.width = (int) CurrWidth;
    txtSongInfo.setLayoutParams(laySongInfo);

    Animation anim = new TranslateAnimation(0, -(CurrWidth - main.getDm().widthPixels + 165), 0, 0);
    anim.setDuration((long) (CurrWidth * 15));
    anim.setStartOffset(2500);
    anim.setRepeatCount(100);
    anim.setInterpolator(new LinearInterpolator());
    anim.setRepeatMode(Animation.REVERSE);
    txtSongInfo.startAnimation(anim);
   }

   // ??????????
   btnListPlay.setOnClickListener(new OnClickListener()
   {
    public void onClick(View v)
    {
     main.getMs().Play(main.getSelectedItemIndex());
    }
   });

   if (main.getScreenOrantation() == 1 || main.getScreenOrantation() == 3)
    layMusicList.setBackgroundResource(R.drawable.bg_land_list_highlight);
   else
    layMusicList.setBackgroundResource(R.drawable.bg_port_list_highlight);
  }

  return convertView;
 }

 public scrMain getMain()
 {
  return main;
 }

 public void setMain(scrMain main)
 {
  this.main = main;
 }

 public List> getLstSong()
 {
  return lstSong;
 }

 public void setLstSong(List> lstSong)
 {
  this.lstSong = lstSong;
 }
}
package com.adserver.adview.samples.advanced;
 
import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.AlphaAnimation;
import android.view.animation.Animation;
import android.view.animation.AnimationSet;
import android.view.animation.LayoutAnimationController;
import android.view.animation.TranslateAnimation;
import android.widget.Button;
import android.widget.LinearLayout;
 
import com.adserver.adview.AdServerView;
import com.adserver.adview.AdServerViewCore.OnAdDownload;
import com.adserver.adview.samples.ApiDemos;
import com.adserver.adview.samples.R;
 
public class AnimAd extends Activity {
    /** Called when the activity is first created. */
    private Context context;
    private LinearLayout linearLayout;
     
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
         
        setContentView(R.layout.animation_ad);
        context = this;
        linearLayout = (LinearLayout) findViewById(R.id.frameAdContent);
          
        final AdServerView adserverView1 = new AdServerView(this,8061,20249);
         
        adserverView1.setId(1);
        adserverView1.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.FILL_PARENT, ApiDemos.BANNER_HEIGHT));
         
        Animation animation = new TranslateAnimation(
                Animation.RELATIVE_TO_SELF, 0.0f, Animation.RELATIVE_TO_SELF, 0.0f,
                Animation.RELATIVE_TO_SELF, -1.0f, Animation.RELATIVE_TO_SELF, -1.0f
            );
        animation.setDuration(Integer.MAX_VALUE);
        animation.setFillAfter(true);
        adserverView1.startAnimation(animation);        
         
        adserverView1.setOnAdDownload(new OnAdDownload() {
            @Override
            public void error(String arg0) {
                 
            }
             
            @Override
            public void end() {
                Animation animation = new TranslateAnimation(
                        Animation.RELATIVE_TO_SELF, 0.0f, Animation.RELATIVE_TO_SELF, 0.0f,
                        Animation.RELATIVE_TO_SELF, -1.0f, Animation.RELATIVE_TO_SELF, 0.0f
                    );
                animation.setDuration(2000);
                adserverView1.startAnimation(animation);    
            }
             
            @Override
            public void begin() {
                 
            }
        });
         
        linearLayout.addView(adserverView1);         
    }
}
package com.MobileAnarchy.Android.Widgets.DockPanel;
 
import android.content.Context;
import android.graphics.Color;
import android.util.AttributeSet;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.animation.AccelerateInterpolator;
import android.view.animation.Animation;
import android.view.animation.DecelerateInterpolator;
import android.view.animation.TranslateAnimation;
import android.view.animation.Animation.AnimationListener;
import android.widget.FrameLayout;
import android.widget.ImageButton;
import android.widget.LinearLayout;
 
public class DockPanel extends LinearLayout {
 
    // =========================================
    // Private members
    // =========================================
 
    private static final String TAG = "DockPanel";
    private DockPosition position;
    private int contentLayoutId;
    private int handleButtonDrawableId;
    private Boolean isOpen;
    private Boolean animationRunning;
    private FrameLayout contentPlaceHolder;
    private ImageButton toggleButton;
    private int animationDuration;
 
    // =========================================
    // Constructors
    // =========================================
 
    public DockPanel(Context context, int contentLayoutId,
            int handleButtonDrawableId, Boolean isOpen) {
        super(context);
 
        this.contentLayoutId = contentLayoutId;
        this.handleButtonDrawableId = handleButtonDrawableId;
        this.isOpen = isOpen;
 
        Init(null);
    }
 
    public DockPanel(Context context, AttributeSet attrs) {
        super(context, attrs);
 
        // to prevent from crashing the designer
        try {
            Init(attrs);
        } catch (Exception ex) {
        }
    }
 
    // =========================================
    // Initialization
    // =========================================
 
    private void Init(AttributeSet attrs) {
        setDefaultValues(attrs);
 
        createHandleToggleButton();
 
        // create the handle container
        FrameLayout handleContainer = new FrameLayout(getContext());
        handleContainer.addView(toggleButton);
 
        // create and populate the panel's container, and inflate it
        contentPlaceHolder = new FrameLayout(getContext());
        String infService = Context.LAYOUT_INFLATER_SERVICE;
        LayoutInflater li = (LayoutInflater) getContext().getSystemService(
                infService);
        li.inflate(contentLayoutId, contentPlaceHolder, true);
 
        // setting the layout of the panel parameters according to the docking
        // position
        if (position == DockPosition.LEFT || position == DockPosition.RIGHT) {
            handleContainer.setLayoutParams(new LayoutParams(
                    android.view.ViewGroup.LayoutParams.WRAP_CONTENT,
                    android.view.ViewGroup.LayoutParams.FILL_PARENT, 1));
            contentPlaceHolder.setLayoutParams(new LayoutParams(
                    android.view.ViewGroup.LayoutParams.WRAP_CONTENT,
                    android.view.ViewGroup.LayoutParams.FILL_PARENT, 1));
        } else {
            handleContainer.setLayoutParams(new LayoutParams(
                    android.view.ViewGroup.LayoutParams.FILL_PARENT,
                    android.view.ViewGroup.LayoutParams.WRAP_CONTENT, 1));
            contentPlaceHolder.setLayoutParams(new LayoutParams(
                    android.view.ViewGroup.LayoutParams.FILL_PARENT,
                    android.view.ViewGroup.LayoutParams.WRAP_CONTENT, 1));
        }
 
        // adding the view to the parent layout according to docking position
        if (position == DockPosition.RIGHT || position == DockPosition.BOTTOM) {
            this.addView(handleContainer);
            this.addView(contentPlaceHolder);
        } else {
            this.addView(contentPlaceHolder);
            this.addView(handleContainer);
        }
 
        if (!isOpen) {
            contentPlaceHolder.setVisibility(GONE);
        }
    }
 
    private void setDefaultValues(AttributeSet attrs) {
        // set default values
        isOpen = true;
        animationRunning = false;
        animationDuration = 500;
        setPosition(DockPosition.RIGHT);
 
        // Try to load values set by xml markup
        if (attrs != null) {
            String namespace = "http://com.MobileAnarchy.Android.Widgets";
 
            animationDuration = attrs.getAttributeIntValue(namespace,
                    "animationDuration", 500);
            contentLayoutId = attrs.getAttributeResourceValue(namespace,
                    "contentLayoutId", 0);
            handleButtonDrawableId = attrs.getAttributeResourceValue(
                    namespace, "handleButtonDrawableResourceId", 0);
            isOpen = attrs.getAttributeBooleanValue(namespace, "isOpen", true);
 
            // Enums are a bit trickier (needs to be parsed)
            try {
                position = DockPosition.valueOf(attrs.getAttributeValue(
                        namespace, "dockPosition").toUpperCase());
                setPosition(position);
            } catch (Exception ex) {
                // Docking to the left is the default behavior
                setPosition(DockPosition.LEFT);
            }
        }
    }
 
    private void createHandleToggleButton() {
        toggleButton = new ImageButton(getContext());
        toggleButton.setPadding(0, 0, 0, 0);
        toggleButton.setLayoutParams(new FrameLayout.LayoutParams(
                android.view.ViewGroup.LayoutParams.WRAP_CONTENT,
                android.view.ViewGroup.LayoutParams.WRAP_CONTENT,
                Gravity.CENTER));
        toggleButton.setBackgroundColor(Color.TRANSPARENT);
        toggleButton.setImageResource(handleButtonDrawableId);
        toggleButton.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                toggle();
            }
        });
    }
 
    private void setPosition(DockPosition position) {
        this.position = position;
        switch (position) {
        case TOP:
            setOrientation(LinearLayout.VERTICAL);
            setGravity(Gravity.TOP);
            break;
        case RIGHT:
            setOrientation(LinearLayout.HORIZONTAL);
            setGravity(Gravity.RIGHT);
            break;
        case BOTTOM:
            setOrientation(LinearLayout.VERTICAL);
            setGravity(Gravity.BOTTOM);
            break;
        case LEFT:
            setOrientation(LinearLayout.HORIZONTAL);
            setGravity(Gravity.LEFT);
            break;
        }
    }
 
    // =========================================
    // Public methods
    // =========================================
 
    public int getAnimationDuration() {
        return animationDuration;
    }
 
    public void setAnimationDuration(int milliseconds) {
        animationDuration = milliseconds;
    }
 
    public Boolean getIsRunning() {
        return animationRunning;
    }
 
    public void open() {
        if (!animationRunning) {
            Log.d(TAG, "Opening...");
 
            Animation animation = createShowAnimation();
            this.setAnimation(animation);
            animation.start();
 
            isOpen = true;
        }
    }
 
    public void close() {
        if (!animationRunning) {
            Log.d(TAG, "Closing...");
 
            Animation animation = createHideAnimation();
            this.setAnimation(animation);
            animation.start();
            isOpen = false;
        }
    }
 
    public void toggle() {
        if (isOpen) {
            close();
        } else {
            open();
        }
    }
 
    // =========================================
    // Private methods
    // =========================================
 
    private Animation createHideAnimation() {
        Animation animation = null;
        switch (position) {
        case TOP:
            animation = new TranslateAnimation(0, 0, 0, -contentPlaceHolder
                    .getHeight());
            break;
        case RIGHT:
            animation = new TranslateAnimation(0, contentPlaceHolder
                    .getWidth(), 0, 0);
            break;
        case BOTTOM:
            animation = new TranslateAnimation(0, 0, 0, contentPlaceHolder
                    .getHeight());
            break;
        case LEFT:
            animation = new TranslateAnimation(0, -contentPlaceHolder
                    .getWidth(), 0, 0);
            break;
        }
 
        animation.setDuration(animationDuration);
        animation.setInterpolator(new AccelerateInterpolator());
        animation.setAnimationListener(new AnimationListener() {
            @Override
            public void onAnimationStart(Animation animation) {
                animationRunning = true;
            }
 
            @Override
            public void onAnimationRepeat(Animation animation) {
            }
 
            @Override
            public void onAnimationEnd(Animation animation) {
                contentPlaceHolder.setVisibility(View.GONE);
                animationRunning = false;
            }
        });
        return animation;
    }
 
    private Animation createShowAnimation() {
        Animation animation = null;
        switch (position) {
        case TOP:
            animation = new TranslateAnimation(0, 0, -contentPlaceHolder
                    .getHeight(), 0);
            break;
        case RIGHT:
            animation = new TranslateAnimation(contentPlaceHolder.getWidth(),
                    0, 0, 0);
            break;
        case BOTTOM:
            animation = new TranslateAnimation(0, 0, contentPlaceHolder
                    .getHeight(), 0);
            break;
        case LEFT:
            animation = new TranslateAnimation(-contentPlaceHolder.getWidth(),
                    0, 0, 0);
            break;
        }
        Log.d(TAG, "Animation duration: " + animationDuration);
        animation.setDuration(animationDuration);
        animation.setInterpolator(new DecelerateInterpolator());
        animation.setAnimationListener(new AnimationListener() {
            @Override
            public void onAnimationStart(Animation animation) {
                animationRunning = true;
                contentPlaceHolder.setVisibility(View.VISIBLE);
                Log.d(TAG, "\"Show\" Animation started");
            }
 
            @Override
            public void onAnimationRepeat(Animation animation) {
            }
 
            @Override
            public void onAnimationEnd(Animation animation) {
                animationRunning = false;
                Log.d(TAG, "\"Show\" Animation ended");
            }
        });
        return animation;
    }
 
}
/*
 * Copyright (C) 2008 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
 
/**
 * the source is come from andorid - 2.1 calculator2
 */
package com.bottleworks.dailymoney.calculator2;
 
import android.content.Context;
import android.text.Editable;
import android.text.Spanned;
import android.text.method.NumberKeyListener;
import android.util.AttributeSet;
import android.view.animation.TranslateAnimation;
import android.text.InputType;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.ViewSwitcher;
import android.graphics.Rect;
import android.graphics.Paint;
 
/**
 * Provides vertical scrolling for the input/result EditText.
 */
class CalculatorDisplay extends ViewSwitcher {
    // only these chars are accepted from keyboard
    private static final char[] ACCEPTED_CHARS = 
        "0123456789.+-*/\u2212\u00d7\u00f7()!%^".toCharArray();
 
    private static final int ANIM_DURATION = 500;
    enum Scroll { UP, DOWN, NONE }
     
    TranslateAnimation inAnimUp;
    TranslateAnimation outAnimUp;
    TranslateAnimation inAnimDown;
    TranslateAnimation outAnimDown;
 
    private Logic mLogic;
    private boolean mComputedLineLength = false;
     
    public CalculatorDisplay(Context context, AttributeSet attrs) {
        super(context, attrs);
    }
     
    @Override
    protected void onFinishInflate() {
        super.onFinishInflate();
        Calculator calc = (Calculator) getContext();
        calc.adjustFontSize((TextView)getChildAt(0));
        calc.adjustFontSize((TextView)getChildAt(1));
    }
 
    @Override
    protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
        super.onLayout(changed, left, top, right, bottom);
        if (!mComputedLineLength) {
            mLogic.setLineLength(getNumberFittingDigits((TextView) getCurrentView()));
            mComputedLineLength = true;
        }
    }
 
    // compute the maximum number of digits that fit in the
    // calculator display without scrolling.
    private int getNumberFittingDigits(TextView display) {
        int available = display.getWidth()
            - display.getTotalPaddingLeft() - display.getTotalPaddingRight();
        Paint paint = display.getPaint();
        float digitWidth = paint.measureText("2222222222") / 10f;
        return (int) (available / digitWidth);
    }
 
    protected void setLogic(Logic logic) {
        mLogic = logic;
        NumberKeyListener calculatorKeyListener =
            new NumberKeyListener() {
                public int getInputType() {
                    // Don't display soft keyboard.
                    return InputType.TYPE_NULL;
                }
             
                protected char[] getAcceptedChars() {
                    return ACCEPTED_CHARS;
                }
 
                public CharSequence filter(CharSequence source, int start, int end,
                                           Spanned dest, int dstart, int dend) {
                    /* the EditText should still accept letters (eg. 'sin')
                       coming from the on-screen touch buttons, so don't filter anything.
                    */
                    return null;
                }
            };
 
        Editable.Factory factory = new CalculatorEditable.Factory(logic);
        for (int i = 0; i < 2; ++i) {
            EditText text = (EditText) getChildAt(i);
            text.setBackgroundDrawable(null);
            text.setEditableFactory(factory);
            text.setKeyListener(calculatorKeyListener);
        }
    }
 
    @Override
    public void setOnKeyListener(OnKeyListener l) {
        getChildAt(0).setOnKeyListener(l);
        getChildAt(1).setOnKeyListener(l);
    }
 
    @Override
    protected void onSizeChanged(int w, int h, int oldW, int oldH) {
        inAnimUp = new TranslateAnimation(0, 0, h, 0);
        inAnimUp.setDuration(ANIM_DURATION);
        outAnimUp = new TranslateAnimation(0, 0, 0, -h);
        outAnimUp.setDuration(ANIM_DURATION);
 
        inAnimDown = new TranslateAnimation(0, 0, -h, 0);
        inAnimDown.setDuration(ANIM_DURATION);
        outAnimDown = new TranslateAnimation(0, 0, 0, h);
        outAnimDown.setDuration(ANIM_DURATION);
    }
 
    void insert(String delta) {
        EditText editor = (EditText) getCurrentView();
        int cursor = editor.getSelectionStart();
        editor.getText().insert(cursor, delta);
    }
 
    EditText getEditText() {
        return (EditText) getCurrentView();
    }
         
    Editable getText() {
        EditText text = (EditText) getCurrentView();
        return text.getText();
    }
     
    void setText(CharSequence text, Scroll dir) {
        if (getText().length() == 0) {
            dir = Scroll.NONE;
        }
         
        if (dir == Scroll.UP) {
            setInAnimation(inAnimUp);
            setOutAnimation(outAnimUp);            
        } else if (dir == Scroll.DOWN) {
            setInAnimation(inAnimDown);
            setOutAnimation(outAnimDown);            
        } else { // Scroll.NONE
            setInAnimation(null);
            setOutAnimation(null);
        }
         
        EditText editText = (EditText) getNextView();
        editText.setText(text);
        //Calculator.log("selection to " + text.length() + "; " + text);
        editText.setSelection(text.length());
        showNext();
    }
     
    void setSelection(int i) {
        EditText text = (EditText) getCurrentView();
        text.setSelection(i);
    }
     
    int getSelectionStart() {
        EditText text = (EditText) getCurrentView();
        return text.getSelectionStart();
    }
     
    @Override
    protected void onFocusChanged(boolean gain, int direction, Rect prev) {
        //Calculator.log("focus " + gain + "; " + direction + "; " + prev);
        if (!gain) {
            requestFocus();
        }
    }
}
package com.adserver.adview.samples.advanced;
 
import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.AlphaAnimation;
import android.view.animation.Animation;
import android.view.animation.AnimationSet;
import android.view.animation.AnimationUtils;
import android.view.animation.LayoutAnimationController;
import android.view.animation.TranslateAnimation;
import android.widget.Button;
import android.widget.LinearLayout;
 
import com.adserver.adview.AdServerView;
import com.adserver.adview.AdServerViewCore.OnAdDownload;
import com.adserver.adview.samples.ApiDemos;
import com.adserver.adview.samples.R;
 
public class AnimAdXML extends Activity {
    /** Called when the activity is first created. */
    private Context context;
    private LinearLayout linearLayout;
     
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
         
        setContentView(R.layout.animation_ad_xml);
        context = this;
         
        final AdServerView adserverView1 = (AdServerView)findViewById(R.id.adServerView);
        final Animation animation = 
            AnimationUtils.loadAnimation(getApplicationContext(),
            R.animator.ad_in_out);
         
        Animation animation2 = new TranslateAnimation(
                Animation.RELATIVE_TO_SELF, 0.0f, Animation.RELATIVE_TO_SELF, 0.0f,
                Animation.RELATIVE_TO_SELF, -1.0f, Animation.RELATIVE_TO_SELF, -1.0f
            );
        animation2.setDuration(Integer.MAX_VALUE);
        animation2.setFillAfter(true);
        adserverView1.startAnimation(animation2);
         
        adserverView1.setOnAdDownload(new OnAdDownload() {
            @Override
            public void error(String arg0) {
                 
            }
             
            @Override
            public void end() {
                adserverView1.startAnimation(animation);    
            }
             
            @Override
            public void begin() {
                 
            }
        });
        /*linearLayout = (LinearLayout) findViewById(R.id.frameAdContent);
          
        final AdServerView adserverView1 = new AdServerView(this,8061,20249);
         
        adserverView1.setId(1);
        adserverView1.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.FILL_PARENT, ApiDemos.BANNER_HEIGHT));
         
        Animation animation = new TranslateAnimation(
                Animation.RELATIVE_TO_SELF, 0.0f, Animation.RELATIVE_TO_SELF, 0.0f,
                Animation.RELATIVE_TO_SELF, -1.0f, Animation.RELATIVE_TO_SELF, -1.0f
            );
        animation.setDuration(Integer.MAX_VALUE);
        animation.setFillAfter(true);
        adserverView1.startAnimation(animation);        
         
        adserverView1.setOnAdDownload(new OnAdDownload() {
            @Override
            public void error(String arg0) {
                 
            }
             
            @Override
            public void end() {
                Animation animation = new TranslateAnimation(
                        Animation.RELATIVE_TO_SELF, 0.0f, Animation.RELATIVE_TO_SELF, 0.0f,
                        Animation.RELATIVE_TO_SELF, -1.0f, Animation.RELATIVE_TO_SELF, 0.0f
                    );
                animation.setDuration(2000);
                adserverView1.startAnimation(animation);    
            }
             
            @Override
            public void begin() {
                 
            }
        });
         
        linearLayout.addView(adserverView1);
         
       /* final AdServerView adserverView2 = new AdServerView(this,8061,20249);
         
        adserverView2.setId(1);
        adserverView2.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.FILL_PARENT, ApiDemos.BANNER_HEIGHT));
         
        Animation animation2 = new AlphaAnimation(0f, 0f);
        animation2.setDuration(Integer.MAX_VALUE);
        animation2.setFillAfter(true);
        adserverView2.startAnimation(animation2);       
         
        adserverView2.setOnAdDownload(new OnAdDownload() {
            @Override
            public void error(String arg0) {
                 
            }
             
            @Override
            public void end() {
                Animation animation = new AlphaAnimation(0.0f, 0.5f);
                animation.setDuration(2000);
                adserverView2.startAnimation(animation);    
            }
             
            @Override
            public void begin() {
                 
            }
        });
         
        linearLayout.addView(adserverView2);*/      
    }
}
package ma.android.fts;
 
import java.util.Random;
 
import android.content.Context;
import android.graphics.Point;
import android.view.animation.AlphaAnimation;
import android.view.animation.Animation;
import android.view.animation.AnimationSet;
import android.view.animation.RotateAnimation;
import android.view.animation.ScaleAnimation;
import android.view.animation.TranslateAnimation;
import android.widget.ImageView;
 
public class AnimationFactory {
     
    final static long ANIMATION_DURATION = 4000;
     
    private static final int ANIMATION_IMAGES = 25; 
     
    private static int[] animationImages = new int[ANIMATION_IMAGES];
    static {
        for (int a=0; a
import sw6.visualschedule.extendedViews.LinkedActivityView;
 
import android.content.Context;
import android.graphics.Rect;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.view.animation.Animation;
import android.view.animation.Animation.AnimationListener;
import android.view.animation.TranslateAnimation;
import android.widget.ImageView;
 
import java.util.Date;
 
/**
 * 
 * @author kfuglsang
 *
 */
public class ActivityImageViewTouchListener implements OnTouchListener {
 
    private final AnimationListener aniListener = new AnimationListener() {
         
        @Override
        public void onAnimationEnd(final Animation animation) {
            isAnimating = false;
            mDraggableImage.setVisibility(View.INVISIBLE);
            mActivityView.setVisibility(View.VISIBLE);                  
            if (mActivityView.getScheduleActivity().getInstanceDate().before(new Date())) {
                mActivityView.startAnimation();             
            }
        }
         
        @Override
        public void onAnimationRepeat(final Animation animation) {
             
        }
         
        @Override
        public void onAnimationStart(final Animation animation) {
            isAnimating = true;
        }
    };
    private Boolean isAnimating = false;
    private transient boolean isOnTopOfTargetView = false;
    private transient StartActivityListener mActivityListener;
    private final transient LinkedActivityView mActivityView;
    private final transient ImageView mDraggableImage;
     
    private transient Rect mHitRect;
     
    /**
     * Initializes the ActivityImageViewTouchListener.
     * 
     * WARNING: High coupling with ActivityList. Should not be used by any other classes than that
     * 
     * @param  context the context in which the listener should run.
     * @param  activityView    the LinkedActivityView to listen for events on. 
     * @param  outerContainerView  the draggable image.
     */
    public ActivityImageViewTouchListener(Context context, LinkedActivityView activityView, ImageView drag) {
        mActivityView = activityView;
        mDraggableImage = drag;
    }
     
    /**
     * Handles on touch events on a view.
     * 
     * @param  view    the view being touched
     * @param  event   the event that has occurred.
     * 
     * @return true if the event is handled by the method.
     */
    @Override
    public boolean onTouch(final View view, final MotionEvent event) {
        Boolean droppedOnActiveZone;
 
        if (isAnimating)
            return false;
         
        switch (event.getActionMasked())
        {
            case MotionEvent.ACTION_MOVE:
                //Move the image to the position underneith user's finger, by modifying padding.
                //TODO: To avoid unnesceary image manipulation, extend ImageView to hold these values.
                mDraggableImage.setPadding((int) event.getRawX()
                        - (mDraggableImage.getDrawable().getMinimumWidth() / 2),
                        (int) event.getRawY()
                                - (int) (mDraggableImage.getDrawable().getMinimumHeight() / 2),
                        0, 0);                    
 
                //Is the dragging image on top of the target view?
                droppedOnActiveZone = mHitRect.contains((int) event.getRawX(),(int) event.getRawY());
                 
                //Avoid constantly setting the drawable by comparing the found boolean to a boolean value
                //that is changed every time droppedOnActiveZone changes.
                if (droppedOnActiveZone != isOnTopOfTargetView) {
                    isOnTopOfTargetView = droppedOnActiveZone;
                    if (droppedOnActiveZone)
                        mActivityListener.draggableImageOverTarget();
                    else
                        mActivityListener.draggableImageAwayFromTarget();
                }
                     
                break;
 
            case MotionEvent.ACTION_UP:
 
                mActivityListener.up();
 
                //Is the dragging view dropped on the drop zone (target view)
                droppedOnActiveZone = mHitRect.contains((int) event.getRawX(), (int) event.getRawY());
                 
                if (droppedOnActiveZone) {
                    //User has dragged activity to dropzone. Check if the step view or countdown view should be shown.
                    //TODO : mCurrentActivity global?
                    mActivityListener.draggableImageDroppedOnTarget();
                } else {
                    //Hide target view (dropzone)
                    mActivityView.getLinkedImageView().setVisibility(View.INVISIBLE);
                     
                    //Create animation that moves activity back to initial position.
                    final int paddingLeft = mDraggableImage.getPaddingLeft();
                    final int paddingTop = mDraggableImage.getPaddingTop();
                     
                    final Rect rectangle = new Rect();
                    view.getHitRect(rectangle);
                    final int[] pos = new int[2];
                    mActivityView.getLocationOnScreen(pos);
                     
                    final int toX = pos[0];
                    final int toY = pos[1];
                    mDraggableImage.setPadding(0, 0, 0, 0);
                     
                    final TranslateAnimation anim = new TranslateAnimation(Animation.ABSOLUTE, paddingLeft, Animation.ABSOLUTE, toX , Animation.ABSOLUTE, paddingTop, Animation.ABSOLUTE, toY);                    
                    anim.setZAdjustment(Animation.ZORDER_TOP);
                     
                    anim.setDuration(500);                    
                    anim.setAnimationListener(aniListener);
                     
                    mDraggableImage.setPadding(0, 0, 0, 0);                    
                    mDraggableImage.startAnimation(anim);
                }
 
                break;
            case MotionEvent.ACTION_DOWN:               
                final int[] location = new int[2];
                mActivityView.getLinkedImageView().getLocationOnScreen(location);           
                mHitRect = new Rect(location[0], location[1], location[0] + mActivityView.getLinkedImageView().getWidth(), location[1] + mActivityView.getHeight());
                               
                mDraggableImage.setPadding((int) event.getRawX()
                        - (mDraggableImage.getDrawable().getMinimumWidth() / 2),
                        (int) event.getRawY()
                                - (int) (mDraggableImage.getDrawable().getMinimumHeight() / 2),
                        0, 0);    
                 
                mActivityView.getLinkedImageView().setVisibility(View.VISIBLE);             
                mActivityListener.down();      
                               
                 
                break;
                 
            default:
                break;
        }
 
        return true;
    }
     
    public void setActivityListener(StartActivityListener activityListener) {
        mActivityListener = activityListener;
    }
}
package jp.android_group.payforward.ui;
 
import android.view.animation.TranslateAnimation;
import android.view.MotionEvent;
import android.view.View;
import android.view.GestureDetector;
import android.widget.FrameLayout;
import android.content.Context;
import android.util.AttributeSet;
import android.util.Log;
 
class PanelSwitcher extends FrameLayout {
    private static final String TAG = "PanelSwitcher";
    private static final int MAJOR_MOVE = 80;
    private static final int ANIM_DURATION = 300;
 
    private GestureDetector mGestureDetector;
    private int mCurrentView;
    private View mChildren[];
 
    private int mWidth;
    private TranslateAnimation inLeft;
    private TranslateAnimation outLeft;
 
    private TranslateAnimation inRight;
    private TranslateAnimation outRight;
     
    private ActiveViewChangeListener listener = null;
     
    public static interface ActiveViewChangeListener {
        public void onActiveViewChanged(int newId);
    }
     
    public void setActiveViewChangeListener(ActiveViewChangeListener l) {
        listener = l;
    }
 
    public PanelSwitcher(Context context, AttributeSet attrs) {
        super(context, attrs);
        mCurrentView = 0;
        mGestureDetector = new GestureDetector(context, new GestureDetector.SimpleOnGestureListener() {
            public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX,
                                   float velocityY) {
                int dx = (int) (e2.getX() - e1.getX());
                // don't accept the fling if it's too short
                // as it may conflict with a button push
                if (Math.abs(dx) > MAJOR_MOVE && Math.abs(velocityX) > Math.abs(velocityY)) {
                    if (velocityX > 0) {
                        moveRight();
                    } else {
                        moveLeft();
                    }
                    return true;
                } else {
                    return false;
                }
            }
        });
    }
 
    public void setCurrentIndex(int current) {
        mCurrentView = current;
        updateCurrentView();
    }
 
    private void updateCurrentView() {
        if (mChildren == null) {
            initChildlen();
        }
        for (int i = mChildren.length-1; i >= 0 ; --i) {
            mChildren[i].setVisibility(i==mCurrentView ? View.VISIBLE : View.GONE);
        }
    }
 
    @Override
    public void onSizeChanged(int w, int h, int oldW, int oldH) {
        mWidth = w;
        inLeft   = new TranslateAnimation(mWidth, 0, 0, 0);
        outLeft  = new TranslateAnimation(0, -mWidth, 0, 0);        
        inRight  = new TranslateAnimation(-mWidth, 0, 0, 0);
        outRight = new TranslateAnimation(0, mWidth, 0, 0);
 
        inLeft.setDuration(ANIM_DURATION);
        outLeft.setDuration(ANIM_DURATION);
        inRight.setDuration(ANIM_DURATION);
        outRight.setDuration(ANIM_DURATION);
    }
     
    protected void initChildlen() {
        int count = getChildCount();
        mChildren = new View[count];
        for (int i = 0; i < count; ++i) {
            mChildren[i] = getChildAt(i);
        }
    }
 
    protected void onFinishInflate() {
        initChildlen();
        updateCurrentView();
    }
 
    @Override
    public boolean onTouchEvent(MotionEvent ev) {
        Log.d(TAG, "onTouch:" + ev);
        final float xf = ev.getX();
        final float yf = ev.getY();
         
        TouchPassThroughListView list = (TouchPassThroughListView)getCurrentView();
        if (list.isEventHandled()) {
            final float scrolledXFloat = xf + getScrollX();
            final float scrolledYFloat = yf + getScrollY();
            final float xc = scrolledXFloat - (float) list.getLeft();
            final float yc = scrolledYFloat - (float) list.getTop();
            ev.setLocation(xc, yc);
            list.dispatchTouchEvent(ev);
        }
 
        ev.setLocation(xf, yf);
        boolean ret = (list != null ? list.isEventHandled() : false);
        ret |= mGestureDetector.onTouchEvent(ev);
        Log.d(TAG, "onTouch ret:" + ret);
        return ret;
    }
 
    @Override
    public boolean onInterceptTouchEvent(MotionEvent event) {
        return mGestureDetector.onTouchEvent(event);
    }
 
    void moveLeft() {
        //  <-- data-blogger-escaped---="" data-blogger-escaped--="" data-blogger-escaped-1="" data-blogger-escaped-iew.gone="" data-blogger-escaped-iew.visible="" data-blogger-escaped-if="" data-blogger-escaped-inleft="" data-blogger-escaped-listener.onactiveviewchanged="" data-blogger-escaped-mchildren.length="" data-blogger-escaped-mchildren="" data-blogger-escaped-mcurrentview="" data-blogger-escaped-moveright="" data-blogger-escaped-outleft="" data-blogger-escaped-setvisibility="" data-blogger-escaped-startanimation="" data-blogger-escaped-void="">
        if (mCurrentView > 0) {
            mChildren[mCurrentView-1].setVisibility(View.VISIBLE);
            mChildren[mCurrentView-1].startAnimation(inRight);
            mChildren[mCurrentView].startAnimation(outRight);
            mChildren[mCurrentView].setVisibility(View.GONE);
            mCurrentView--;
            listener.onActiveViewChanged(mCurrentView);
        }
    }
 
    public int getCurrentIndex() {
        return mCurrentView;
    }
     
    public View getCurrentView() {
        return mChildren[mCurrentView];
    }
}
/*
 * Copyright (C) 2007 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
 
package com.example.android.apis.view;
 
import android.app.ListActivity;
import android.os.Bundle;
import android.view.animation.AlphaAnimation;
import android.view.animation.Animation;
import android.view.animation.AnimationSet;
import android.view.animation.LayoutAnimationController;
import android.view.animation.TranslateAnimation;
import android.widget.ArrayAdapter;
import android.widget.ListView;
 
public class LayoutAnimation2 extends ListActivity {
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
 
        setListAdapter(new ArrayAdapter(this,
                android.R.layout.simple_list_item_1, mStrings));
 
        AnimationSet set = new AnimationSet(true);
 
        Animation animation = new AlphaAnimation(0.0f, 1.0f);
        animation.setDuration(50);
        set.addAnimation(animation);
 
        animation = new TranslateAnimation(
            Animation.RELATIVE_TO_SELF, 0.0f,Animation.RELATIVE_TO_SELF, 0.0f,
            Animation.RELATIVE_TO_SELF, -1.0f,Animation.RELATIVE_TO_SELF, 0.0f
        );
        animation.setDuration(100);
        set.addAnimation(animation);
 
        LayoutAnimationController controller =
                new LayoutAnimationController(set, 0.5f);
        ListView listView = getListView();        
        listView.setLayoutAnimation(controller);
    }
 
    private String[] mStrings = {
        "Bordeaux",
        "Lyon",
        "Marseille",
        "Nancy",
        "Paris",
        "Toulouse",
        "Strasbourg"
    };
}

No comments:

Post a Comment