Android搜索關鍵字飛入飛出效果





 






實現該效果需要解決以下五點:

1.佈局的選用。
2.確定動畫區域,即佈局的寬高。
3.對關鍵字座標的隨機分配。
4.對隨機分配的座標進行向中心靠攏。
5.動畫的實現。

本文內容歸CSDN博客博主Sodino 所有
轉載請註明出處:http://blog.csdn.net/sodino/article/details/7176796

下面各個擊破:
1.佈局的選用。
    在五種常用佈局中,可實現此效果的有AbsoluteLayout、FrameLayout、RelativeLayout三種。一開始我選用的AbsoluteLayout,運行結果出來後,發現AbsoluteLayout下的TextView一旦超出其顯示範圍,超出的範圍將無法顯示,而餘下的兩種佈局,其超出的範圍會自動換行顯示出來(TextView長度超出父組件顯示範圍可在代碼中避免,此處僅是舉例,說明AbsoluteLayout的先天不足)。另,官方已不再推薦使用AbsoluteLayout,所以本處憑個人喜好我選用FrameLayout。
    
    FrameLayout如何實現AbsoluteLayout對其子組件進行定點放置呢?答案在FrameLayout.LayoutParams上。該類有相關屬性爲leftMargin及topMargin。要將子組件左上角定點放置在其父組件中的(x,y)處,僅需對leftMargin賦值爲x,對topMargin賦值爲y即可。
    
2.確定動畫區域,即佈局的寬高。
    在對顯示關鍵字TextView進行分配座標之前,應該要先知道父組件的寬高各有多少可供隨機分配。
    獲取寬高使用到OnGlobalLayoutListener。本例中KeywordsFlow繼承自FrameLayout,同時也實現了OnGlobalLayoutListener接口,在其初始化方法init()中設置了監聽getViewTreeObserver().addOnGlobalLayoutListener(this);
    當監聽事件被觸發時,即可獲取而已的寬高。

[java] view plaincopy
  1. public void onGlobalLayout() {  
  2.     int tmpW = getWidth();  
  3.     int tmpH = getHeight();  
  4.     if (width != tmpW || height != tmpH) {  
  5.         width = tmpW;  
  6.         height = tmpH;  
  7.         show();  
  8.     }  
  9. }  


    
3.對關鍵字座標的隨機分配。
    TextView座標的隨機是否到位分配決定着整體效果的好壞。
    本例設定關鍵字最多爲10個,在佈局的X Y軸上各自進行10等分。每個關鍵字依照其添加順序隨機各自在X軸和Y軸上選擇等分後的10點中的某個點爲margin的值。此值爲糙值,需要對X軸進行越界修正,對Y軸進行向中心靠攏修正。對X軸座標的修正爲如下:

[java] view plaincopy
  1.     // 獲取文本長度  
  2. Paint paint = txt.getPaint();  
  3. int strWidth = (int) Math.ceil(paint.measureText(keyword));  
  4. xy[IDX_TXT_LENGTH] = strWidth;  
  5. // 第一次修正:修正x座標  
  6. if (xy[IDX_X] + strWidth > width - (xItem >> 1)) {  
  7.     int baseX = width - strWidth;  
  8.     // 減少文本右邊緣一樣的概率  
  9.     xy[IDX_X] = baseX - xItem + random.nextInt(xItem >> 1);  
  10. else if (xy[IDX_X] == 0) {  
  11.     // 減少文本左邊緣一樣的概率  
  12.     xy[IDX_X] = Math.max(random.nextInt(xItem), xItem / 3);  
  13. }  


4.對隨機分配的座標進行向中心靠攏。
    此操作將修正Y軸座標。
    由於隨機分配中,可能出現某個關鍵字在朝中心點方向上的空間中再沒有其它關鍵字了,此時該關鍵字在Y軸上應該朝中心點靠攏。實現代碼如下:
[java] view plaincopy
  1.     // 第二次修正:修正y座標  
  2. int yDistance = iXY[IDX_Y] - yCenter;  
  3. // 對於最靠近中心點的,其值不會大於yItem<br/>  
  4. // 對於可以一路下降到中心點的,則該值也是其應調整的大小<br/>  
  5. int yMove = Math.abs(yDistance);  
  6. inner: for (int k = i - 1; k >= 0; k--) {  
  7.     int[] kXY = (int[]) listTxt.get(k).getTag();  
  8.     int startX = kXY[IDX_X];  
  9.     int endX = startX + kXY[IDX_TXT_LENGTH];  
  10.     // y軸以中心點爲分隔線,在同一側  
  11.     if (yDistance * (kXY[IDX_Y] - yCenter) > 0) {  
  12.         // Log.d("ANDROID_LAB", "compare:" +  
  13.         // listTxt.get(k).getText());  
  14.         if (isXMixed(startX, endX, iXY[IDX_X], iXY[IDX_X] + iXY[IDX_TXT_LENGTH])) {  
  15.             int tmpMove = Math.abs(iXY[IDX_Y] - kXY[IDX_Y]);  
  16.             if (tmpMove > yItem) {  
  17.                 yMove = tmpMove;  
  18.             } else if (yMove > 0) {  
  19.                 // 取消默認值。  
  20.                 yMove = 0;  
  21.             }  
  22.             // Log.d("ANDROID_LAB", "break");  
  23.             break inner;  
  24.         }  
  25.     }  
  26. }  
  27. // Log.d("ANDROID_LAB", txt.getText() + " yMove=" + yMove);  
  28. if (yMove > yItem) {  
  29.     int maxMove = yMove - yItem;  
  30.     int randomMove = random.nextInt(maxMove);  
  31.     int realMove = Math.max(randomMove, maxMove >> 1) * yDistance / Math.abs(yDistance);  
  32.     iXY[IDX_Y] = iXY[IDX_Y] - realMove;  
  33.     iXY[IDX_DIS_Y] = Math.abs(iXY[IDX_Y] - yCenter);  
  34.     // 已經調整過前i個需要再次排序  
  35.     sortXYList(listTxt, i + 1);  
  36. }  


            
            
5.動畫的實現。
    每個TextView的動畫都有包括三部分:伸縮動畫ScaleAnimation、透明度漸變動畫AlphaAnimation及位移動畫TranslateAnimation。以上三個動畫中除了位移動畫是獨立的,其它兩種動畫都是可以共用的。三種動畫的組合使用AnimationSet拼裝在一起同時作用在TextView上。動畫的實現如下:
[java] view plaincopy
  1. public AnimationSet getAnimationSet(int[] xy, int xCenter, int yCenter, int type) {  
  2.     AnimationSet animSet = new AnimationSet(true);  
  3.     animSet.setInterpolator(interpolator);  
  4.     if (type == OUTSIDE_TO_LOCATION) {  
  5.         animSet.addAnimation(animAlpha2Opaque);  
  6.         animSet.addAnimation(animScaleLarge2Normal);  
  7.         TranslateAnimation translate = new TranslateAnimation(  
  8.                 (xy[IDX_X] + (xy[IDX_TXT_LENGTH] >> 1) - xCenter) << 10, (xy[IDX_Y] - yCenter) << 10);  
  9.         animSet.addAnimation(translate);  
  10.     } else if (type == LOCATION_TO_OUTSIDE) {  
  11.         animSet.addAnimation(animAlpha2Transparent);  
  12.         animSet.addAnimation(animScaleNormal2Large);  
  13.         TranslateAnimation translate = new TranslateAnimation(0,  
  14.                 (xy[IDX_X] + (xy[IDX_TXT_LENGTH] >> 1) - xCenter) << 10, (xy[IDX_Y] - yCenter) << 1);  
  15.         animSet.addAnimation(translate);  
  16.     } else if (type == LOCATION_TO_CENTER) {  
  17.         animSet.addAnimation(animAlpha2Transparent);  
  18.         animSet.addAnimation(animScaleNormal2Zero);  
  19.         TranslateAnimation translate = new TranslateAnimation(0, (-xy[IDX_X] + xCenter), 0, (-xy[IDX_Y] + yCenter));  
  20.         animSet.addAnimation(translate);  
  21.     } else if (type == CENTER_TO_LOCATION) {  
  22.         animSet.addAnimation(animAlpha2Opaque);  
  23.         animSet.addAnimation(animScaleZero2Normal);  
  24.         TranslateAnimation translate = new TranslateAnimation((-xy[IDX_X] + xCenter), 0, (-xy[IDX_Y] + yCenter), 0);  
  25.         animSet.addAnimation(translate);  
  26.     }  
  27.     animSet.setDuration(animDuration);  
  28.     return animSet;  
  29. }  


    
    最後有個小點需要再次提醒下,使用KeywordsFlow時,在Eclipse開發環境下導出混淆包時,需要在proguard.cfg中添加:-keep public class * extends android.widget.FrameLayout
    否則將會提示無法找到該類。
    好了,文嗦嗦的東西到此結束,貼上Java代碼如下,xml代碼請根據效果圖自己鼓搗吧。

[java] view plaincopy
  1. ActKeywordAnim.java  
  2.   
  3. package lab.sodino.searchkeywordanim;  
  4.   
  5. import java.util.Random;  
  6.   
  7. import android.app.Activity;  
  8. import android.content.Intent;  
  9. import android.net.Uri;  
  10. import android.os.Bundle;  
  11. import android.view.View;  
  12. import android.view.View.OnClickListener;  
  13. import android.widget.Button;  
  14. import android.widget.TextView;  
  15.   
  16. /** 
  17.  * @author Sodino E-mail:[email protected] 
  18.  * @version Time:2011-12-26 下午03:34:16 
  19.  */  
  20. public class ActKeywordAnim extends Activity implements OnClickListener {  
  21.     public static final String[] keywords = { "QQ""Sodino""APK""GFW""鉛筆",//  
  22.             "短信""桌面精靈""MacBook Pro""平板電腦""雅詩蘭黛",//  
  23.             "卡西歐 TR-100""筆記本""SPY Mouse""Thinkpad E40""捕魚達人",//  
  24.             "內存清理""地圖""導航""鬧鐘""主題",//  
  25.             "通訊錄""播放器""CSDN leak""安全""3D",//  
  26.             "美女""天氣""4743G""戴爾""聯想",//  
  27.             "歐朋""瀏覽器""憤怒的小鳥""mmShow""網易公開課",//  
  28.             "iciba""油水關係""網遊App""互聯網""365日曆",//  
  29.             "臉部識別""Chrome""Safari""中國版Siri""A5處理器",//  
  30.             "iPhone4S""摩托 ME525""魅族 M9""尼康 S2500" };  
  31.     private KeywordsFlow keywordsFlow;  
  32.     private Button btnIn, btnOut;  
  33.   
  34.     public void onCreate(Bundle savedInstanceState) {  
  35.         super.onCreate(savedInstanceState);  
  36.         setContentView(R.layout.main);  
  37.         btnIn = (Button) findViewById(R.id.btnIn);  
  38.         btnOut = (Button) findViewById(R.id.btnOut);  
  39.         btnIn.setOnClickListener(this);  
  40.         btnOut.setOnClickListener(this);  
  41.         keywordsFlow = (KeywordsFlow) findViewById(R.id.keywordsFlow);  
  42.         keywordsFlow.setDuration(800l);  
  43.         keywordsFlow.setOnItemClickListener(this);  
  44.         // 添加  
  45.         feedKeywordsFlow(keywordsFlow, keywords);  
  46.         keywordsFlow.go2Show(KeywordsFlow.ANIMATION_IN);  
  47.     }  
  48.   
  49.     private static void feedKeywordsFlow(KeywordsFlow keywordsFlow, String[] arr) {  
  50.         Random random = new Random();  
  51.         for (int i = 0; i < KeywordsFlow.MAX; i++) {  
  52.             int ran = random.nextInt(arr.length);  
  53.             String tmp = arr[ran];  
  54.             keywordsFlow.feedKeyword(tmp);  
  55.         }  
  56.     }  
  57.   
  58.     @Override  
  59.     public void onClick(View v) {  
  60.         if (v == btnIn) {  
  61.             keywordsFlow.rubKeywords();  
  62.             // keywordsFlow.rubAllViews();  
  63.             feedKeywordsFlow(keywordsFlow, keywords);  
  64.             keywordsFlow.go2Show(KeywordsFlow.ANIMATION_IN);  
  65.         } else if (v == btnOut) {  
  66.             keywordsFlow.rubKeywords();  
  67.             // keywordsFlow.rubAllViews();  
  68.             feedKeywordsFlow(keywordsFlow, keywords);  
  69.             keywordsFlow.go2Show(KeywordsFlow.ANIMATION_OUT);  
  70.         } else if (v instanceof TextView) {  
  71.             String keyword = ((TextView) v).getText().toString();  
  72.             Intent intent = new Intent();  
  73.             intent.setAction(Intent.ACTION_VIEW);  
  74.             intent.addCategory(Intent.CATEGORY_DEFAULT);  
  75.             intent.setData(Uri.parse("http://www.google.com.hk/#q=" + keyword));  
  76.             startActivity(intent);  
  77.         }  
  78.     }  
  79. }  

[java] view plaincopy
  1. KeywordsFlow.java  
  2.   
  3. package lab.sodino.searchkeywordanim;  
  4.   
  5. import java.util.LinkedList;  
  6. import java.util.Random;  
  7. import java.util.Vector;  
  8.   
  9. import android.content.Context;  
  10. import android.graphics.Paint;  
  11. import android.util.AttributeSet;  
  12. import android.util.TypedValue;  
  13. import android.view.Gravity;  
  14. import android.view.View;  
  15. import android.view.ViewTreeObserver.OnGlobalLayoutListener;  
  16. import android.view.animation.AlphaAnimation;  
  17. import android.view.animation.Animation;  
  18. import android.view.animation.Animation.AnimationListener;  
  19. import android.view.animation.AnimationSet;  
  20. import android.view.animation.AnimationUtils;  
  21. import android.view.animation.Interpolator;  
  22. import android.view.animation.ScaleAnimation;  
  23. import android.view.animation.TranslateAnimation;  
  24. import android.widget.FrameLayout;  
  25. import android.widget.TextView;  
  26.   
  27. /** 
  28.  * 注意,出包時出混淆包,應在proguard.cfg中加入:<br/> 
  29.  * -keep public class * extends android.widget.FrameLayout<br/> 
  30.  *  
  31.  * @author Sodino E-mail:[email protected] 
  32.  * @version Time:2011-12-26 下午03:34:16 
  33.  */  
  34. public class KeywordsFlow extends FrameLayout implements OnGlobalLayoutListener {  
  35.     public static final int IDX_X = 0;  
  36.     public static final int IDX_Y = 1;  
  37.     public static final int IDX_TXT_LENGTH = 2;  
  38.     public static final int IDX_DIS_Y = 3;  
  39.     /** 由外至內的動畫。 */  
  40.     public static final int ANIMATION_IN = 1;  
  41.     /** 由內至外的動畫。 */  
  42.     public static final int ANIMATION_OUT = 2;  
  43.     /** 位移動畫類型:從外圍移動到座標點。 */  
  44.     public static final int OUTSIDE_TO_LOCATION = 1;  
  45.     /** 位移動畫類型:從座標點移動到外圍。 */  
  46.     public static final int LOCATION_TO_OUTSIDE = 2;  
  47.     /** 位移動畫類型:從中心點移動到座標點。 */  
  48.     public static final int CENTER_TO_LOCATION = 3;  
  49.     /** 位移動畫類型:從座標點移動到中心點。 */  
  50.     public static final int LOCATION_TO_CENTER = 4;  
  51.     public static final long ANIM_DURATION = 800l;  
  52.     public static final int MAX = 10;  
  53.     public static final int TEXT_SIZE_MAX = 25;  
  54.     public static final int TEXT_SIZE_MIN = 15;  
  55.     private OnClickListener itemClickListener;  
  56.     private static Interpolator interpolator;  
  57.     private static AlphaAnimation animAlpha2Opaque;  
  58.     private static AlphaAnimation animAlpha2Transparent;  
  59.     private static ScaleAnimation animScaleLarge2Normal, animScaleNormal2Large, animScaleZero2Normal,  
  60.             animScaleNormal2Zero;  
  61.     /** 存儲顯示的關鍵字。 */  
  62.     private Vector<String> vecKeywords;  
  63.     private int width, height;  
  64.     /** 
  65.      * go2Show()中被賦值爲true,標識開發人員觸發其開始動畫顯示。<br/> 
  66.      * 本標識的作用是防止在填充keywrods未完成的過程中獲取到width和height後提前啓動動畫。<br/> 
  67.      * 在show()方法中其被賦值爲false。<br/> 
  68.      * 真正能夠動畫顯示的另一必要條件:width 和 height不爲0。<br/> 
  69.      */  
  70.     private boolean enableShow;  
  71.     private Random random;  
  72.     /** 
  73.      * @see ANIMATION_IN 
  74.      * @see ANIMATION_OUT 
  75.      * @see OUTSIDE_TO_LOCATION 
  76.      * @see LOCATION_TO_OUTSIDE 
  77.      * @see LOCATION_TO_CENTER 
  78.      * @see CENTER_TO_LOCATION 
  79.      * */  
  80.     private int txtAnimInType, txtAnimOutType;  
  81.     /** 最近一次啓動動畫顯示的時間。 */  
  82.     private long lastStartAnimationTime;  
  83.     /** 動畫運行時間。 */  
  84.     private long animDuration;  
  85.   
  86.     public KeywordsFlow(Context context, AttributeSet attrs, int defStyle) {  
  87.         super(context, attrs, defStyle);  
  88.         init();  
  89.     }  
  90.   
  91.     public KeywordsFlow(Context context, AttributeSet attrs) {  
  92.         super(context, attrs);  
  93.         init();  
  94.     }  
  95.   
  96.     public KeywordsFlow(Context context) {  
  97.         super(context);  
  98.         init();  
  99.     }  
  100.   
  101.     private void init() {  
  102.         lastStartAnimationTime = 0l;  
  103.         animDuration = ANIM_DURATION;  
  104.         random = new Random();  
  105.         vecKeywords = new Vector<String>(MAX);  
  106.         getViewTreeObserver().addOnGlobalLayoutListener(this);  
  107.         interpolator = AnimationUtils.loadInterpolator(getContext(), android.R.anim.decelerate_interpolator);  
  108.         animAlpha2Opaque = new AlphaAnimation(0.0f, 1.0f);  
  109.         animAlpha2Transparent = new AlphaAnimation(1.0f, 0.0f);  
  110.         animScaleLarge2Normal = new ScaleAnimation(2121);  
  111.         animScaleNormal2Large = new ScaleAnimation(1212);  
  112.         animScaleZero2Normal = new ScaleAnimation(0101);  
  113.         animScaleNormal2Zero = new ScaleAnimation(1010);  
  114.     }  
  115.   
  116.     public long getDuration() {  
  117.         return animDuration;  
  118.     }  
  119.   
  120.     public void setDuration(long duration) {  
  121.         animDuration = duration;  
  122.     }  
  123.   
  124.     public boolean feedKeyword(String keyword) {  
  125.         boolean result = false;  
  126.         if (vecKeywords.size() < MAX) {  
  127.             result = vecKeywords.add(keyword);  
  128.         }  
  129.         return result;  
  130.     }  
  131.   
  132.     /** 
  133.      * 開始動畫顯示。<br/> 
  134.      * 之前已經存在的TextView將會顯示退出動畫。<br/> 
  135.      *  
  136.      * @return 正常顯示動畫返回true;反之爲false。返回false原因如下:<br/> 
  137.      *         1.時間上不允許,受lastStartAnimationTime的制約;<br/> 
  138.      *         2.未獲取到width和height的值。<br/> 
  139.      */  
  140.     public boolean go2Show(int animType) {  
  141.         if (System.currentTimeMillis() - lastStartAnimationTime > animDuration) {  
  142.             enableShow = true;  
  143.             if (animType == ANIMATION_IN) {  
  144.                 txtAnimInType = OUTSIDE_TO_LOCATION;  
  145.                 txtAnimOutType = LOCATION_TO_CENTER;  
  146.             } else if (animType == ANIMATION_OUT) {  
  147.                 txtAnimInType = CENTER_TO_LOCATION;  
  148.                 txtAnimOutType = LOCATION_TO_OUTSIDE;  
  149.             }  
  150.             disapper();  
  151.             boolean result = show();  
  152.             return result;  
  153.         }  
  154.         return false;  
  155.     }  
  156.   
  157.     private void disapper() {  
  158.         int size = getChildCount();  
  159.         for (int i = size - 1; i >= 0; i--) {  
  160.             final TextView txt = (TextView) getChildAt(i);  
  161.             if (txt.getVisibility() == View.GONE) {  
  162.                 removeView(txt);  
  163.                 continue;  
  164.             }  
  165.             FrameLayout.LayoutParams layParams = (LayoutParams) txt.getLayoutParams();  
  166.             // Log.d("ANDROID_LAB", txt.getText() + " leftM=" +  
  167.             // layParams.leftMargin + " topM=" + layParams.topMargin  
  168.             // + " width=" + txt.getWidth());  
  169.             int[] xy = new int[] { layParams.leftMargin, layParams.topMargin, txt.getWidth() };  
  170.             AnimationSet animSet = getAnimationSet(xy, (width >> 1), (height >> 1), txtAnimOutType);  
  171.             txt.startAnimation(animSet);  
  172.             animSet.setAnimationListener(new AnimationListener() {  
  173.                 public void onAnimationStart(Animation animation) {  
  174.                 }  
  175.   
  176.                 public void onAnimationRepeat(Animation animation) {  
  177.                 }  
  178.   
  179.                 public void onAnimationEnd(Animation animation) {  
  180.                     txt.setOnClickListener(null);  
  181.                     txt.setClickable(false);  
  182.                     txt.setVisibility(View.GONE);  
  183.                 }  
  184.             });  
  185.         }  
  186.     }  
  187.   
  188.     private boolean show() {  
  189.         if (width > 0 && height > 0 && vecKeywords != null && vecKeywords.size() > 0 && enableShow) {  
  190.             enableShow = false;  
  191.             lastStartAnimationTime = System.currentTimeMillis();  
  192.             int xCenter = width >> 1, yCenter = height >> 1;  
  193.             int size = vecKeywords.size();  
  194.             int xItem = width / size, yItem = height / size;  
  195.             // Log.d("ANDROID_LAB", "--------------------------width=" + width +  
  196.             // " height=" + height + "  xItem=" + xItem  
  197.             // + " yItem=" + yItem + "---------------------------");  
  198.             LinkedList<Integer> listX = new LinkedList<Integer>(), listY = new LinkedList<Integer>();  
  199.             for (int i = 0; i < size; i++) {  
  200.                 // 準備隨機候選數,分別對應x/y軸位置  
  201.                 listX.add(i * xItem);  
  202.                 listY.add(i * yItem + (yItem >> 2));  
  203.             }  
  204.             // TextView[] txtArr = new TextView[size];  
  205.             LinkedList<TextView> listTxtTop = new LinkedList<TextView>();  
  206.             LinkedList<TextView> listTxtBottom = new LinkedList<TextView>();  
  207.             for (int i = 0; i < size; i++) {  
  208.                 String keyword = vecKeywords.get(i);  
  209.                 // 隨機顏色  
  210.                 int ranColor = 0xff000000 | random.nextInt(0x0077ffff);  
  211.                 // 隨機位置,糙值  
  212.                 int xy[] = randomXY(random, listX, listY, xItem);  
  213.                 // 隨機字體大小  
  214.                 int txtSize = TEXT_SIZE_MIN + random.nextInt(TEXT_SIZE_MAX - TEXT_SIZE_MIN + 1);  
  215.                 // 實例化TextView  
  216.                 final TextView txt = new TextView(getContext());  
  217.                 txt.setOnClickListener(itemClickListener);  
  218.                 txt.setText(keyword);  
  219.                 txt.setTextColor(ranColor);  
  220.                 txt.setTextSize(TypedValue.COMPLEX_UNIT_SP, txtSize);  
  221.                 txt.setShadowLayer(2220xff696969);  
  222.                 txt.setGravity(Gravity.CENTER);  
  223.                 // 獲取文本長度  
  224.                 Paint paint = txt.getPaint();  
  225.                 int strWidth = (int) Math.ceil(paint.measureText(keyword));  
  226.                 xy[IDX_TXT_LENGTH] = strWidth;  
  227.                 // 第一次修正:修正x座標  
  228.                 if (xy[IDX_X] + strWidth > width - (xItem >> 1)) {  
  229.                     int baseX = width - strWidth;  
  230.                     // 減少文本右邊緣一樣的概率  
  231.                     xy[IDX_X] = baseX - xItem + random.nextInt(xItem >> 1);  
  232.                 } else if (xy[IDX_X] == 0) {  
  233.                     // 減少文本左邊緣一樣的概率  
  234.                     xy[IDX_X] = Math.max(random.nextInt(xItem), xItem / 3);  
  235.                 }  
  236.                 xy[IDX_DIS_Y] = Math.abs(xy[IDX_Y] - yCenter);  
  237.                 txt.setTag(xy);  
  238.                 if (xy[IDX_Y] > yCenter) {  
  239.                     listTxtBottom.add(txt);  
  240.                 } else {  
  241.                     listTxtTop.add(txt);  
  242.                 }  
  243.             }  
  244.             attach2Screen(listTxtTop, xCenter, yCenter, yItem);  
  245.             attach2Screen(listTxtBottom, xCenter, yCenter, yItem);  
  246.             return true;  
  247.         }  
  248.         return false;  
  249.     }  
  250.   
  251.     /** 修正TextView的Y座標將將其添加到容器上。 */  
  252.     private void attach2Screen(LinkedList<TextView> listTxt, int xCenter, int yCenter, int yItem) {  
  253.         int size = listTxt.size();  
  254.         sortXYList(listTxt, size);  
  255.         for (int i = 0; i < size; i++) {  
  256.             TextView txt = listTxt.get(i);  
  257.             int[] iXY = (int[]) txt.getTag();  
  258.             // Log.d("ANDROID_LAB", "fix[  " + txt.getText() + "  ] x:" +  
  259.             // iXY[IDX_X] + " y:" + iXY[IDX_Y] + " r2="  
  260.             // + iXY[IDX_DIS_Y]);  
  261.             // 第二次修正:修正y座標  
  262.             int yDistance = iXY[IDX_Y] - yCenter;  
  263.             // 對於最靠近中心點的,其值不會大於yItem<br/>  
  264.             // 對於可以一路下降到中心點的,則該值也是其應調整的大小<br/>  
  265.             int yMove = Math.abs(yDistance);  
  266.             inner: for (int k = i - 1; k >= 0; k--) {  
  267.                 int[] kXY = (int[]) listTxt.get(k).getTag();  
  268.                 int startX = kXY[IDX_X];  
  269.                 int endX = startX + kXY[IDX_TXT_LENGTH];  
  270.                 // y軸以中心點爲分隔線,在同一側  
  271.                 if (yDistance * (kXY[IDX_Y] - yCenter) > 0) {  
  272.                     // Log.d("ANDROID_LAB", "compare:" +  
  273.                     // listTxt.get(k).getText());  
  274.                     if (isXMixed(startX, endX, iXY[IDX_X], iXY[IDX_X] + iXY[IDX_TXT_LENGTH])) {  
  275.                         int tmpMove = Math.abs(iXY[IDX_Y] - kXY[IDX_Y]);  
  276.                         if (tmpMove > yItem) {  
  277.                             yMove = tmpMove;  
  278.                         } else if (yMove > 0) {  
  279.                             // 取消默認值。  
  280.                             yMove = 0;  
  281.                         }  
  282.                         // Log.d("ANDROID_LAB", "break");  
  283.                         break inner;  
  284.                     }  
  285.                 }  
  286.             }  
  287.             // Log.d("ANDROID_LAB", txt.getText() + " yMove=" + yMove);  
  288.             if (yMove > yItem) {  
  289.                 int maxMove = yMove - yItem;  
  290.                 int randomMove = random.nextInt(maxMove);  
  291.                 int realMove = Math.max(randomMove, maxMove >> 1) * yDistance / Math.abs(yDistance);  
  292.                 iXY[IDX_Y] = iXY[IDX_Y] - realMove;  
  293.                 iXY[IDX_DIS_Y] = Math.abs(iXY[IDX_Y] - yCenter);  
  294.                 // 已經調整過前i個需要再次排序  
  295.                 sortXYList(listTxt, i + 1);  
  296.             }  
  297.             FrameLayout.LayoutParams layParams = new FrameLayout.LayoutParams(FrameLayout.LayoutParams.WRAP_CONTENT,  
  298.                     FrameLayout.LayoutParams.WRAP_CONTENT);  
  299.             layParams.gravity = Gravity.LEFT | Gravity.TOP;  
  300.             layParams.leftMargin = iXY[IDX_X];  
  301.             layParams.topMargin = iXY[IDX_Y];  
  302.             addView(txt, layParams);  
  303.             // 動畫  
  304.             AnimationSet animSet = getAnimationSet(iXY, xCenter, yCenter, txtAnimInType);  
  305.             txt.startAnimation(animSet);  
  306.         }  
  307.     }  
  308.   
  309.     public AnimationSet getAnimationSet(int[] xy, int xCenter, int yCenter, int type) {  
  310.         AnimationSet animSet = new AnimationSet(true);  
  311.         animSet.setInterpolator(interpolator);  
  312.         if (type == OUTSIDE_TO_LOCATION) {  
  313.             animSet.addAnimation(animAlpha2Opaque);  
  314.             animSet.addAnimation(animScaleLarge2Normal);  
  315.             TranslateAnimation translate = new TranslateAnimation(  
  316.                     (xy[IDX_X] + (xy[IDX_TXT_LENGTH] >> 1) - xCenter) << 10, (xy[IDX_Y] - yCenter) << 10);  
  317.             animSet.addAnimation(translate);  
  318.         } else if (type == LOCATION_TO_OUTSIDE) {  
  319.             animSet.addAnimation(animAlpha2Transparent);  
  320.             animSet.addAnimation(animScaleNormal2Large);  
  321.             TranslateAnimation translate = new TranslateAnimation(0,  
  322.                     (xy[IDX_X] + (xy[IDX_TXT_LENGTH] >> 1) - xCenter) << 10, (xy[IDX_Y] - yCenter) << 1);  
  323.             animSet.addAnimation(translate);  
  324.         } else if (type == LOCATION_TO_CENTER) {  
  325.             animSet.addAnimation(animAlpha2Transparent);  
  326.             animSet.addAnimation(animScaleNormal2Zero);  
  327.             TranslateAnimation translate = new TranslateAnimation(0, (-xy[IDX_X] + xCenter), 0, (-xy[IDX_Y] + yCenter));  
  328.             animSet.addAnimation(translate);  
  329.         } else if (type == CENTER_TO_LOCATION) {  
  330.             animSet.addAnimation(animAlpha2Opaque);  
  331.             animSet.addAnimation(animScaleZero2Normal);  
  332.             TranslateAnimation translate = new TranslateAnimation((-xy[IDX_X] + xCenter), 0, (-xy[IDX_Y] + yCenter), 0);  
  333.             animSet.addAnimation(translate);  
  334.         }  
  335.         animSet.setDuration(animDuration);  
  336.         return animSet;  
  337.     }  
  338.   
  339.     /** 
  340.      * 根據與中心點的距離由近到遠進行冒泡排序。 
  341.      *  
  342.      * @param endIdx 
  343.      *            起始位置。 
  344.      * @param txtArr 
  345.      *            待排序的數組。 
  346.      *  
  347.      */  
  348.     private void sortXYList(LinkedList<TextView> listTxt, int endIdx) {  
  349.         for (int i = 0; i < endIdx; i++) {  
  350.             for (int k = i + 1; k < endIdx; k++) {  
  351.                 if (((int[]) listTxt.get(k).getTag())[IDX_DIS_Y] < ((int[]) listTxt.get(i).getTag())[IDX_DIS_Y]) {  
  352.                     TextView iTmp = listTxt.get(i);  
  353.                     TextView kTmp = listTxt.get(k);  
  354.                     listTxt.set(i, kTmp);  
  355.                     listTxt.set(k, iTmp);  
  356.                 }  
  357.             }  
  358.         }  
  359.     }  
  360.   
  361.     /** A線段與B線段所代表的直線在X軸映射上是否有交集。 */  
  362.     private boolean isXMixed(int startA, int endA, int startB, int endB) {  
  363.         boolean result = false;  
  364.         if (startB >= startA && startB <= endA) {  
  365.             result = true;  
  366.         } else if (endB >= startA && endB <= endA) {  
  367.             result = true;  
  368.         } else if (startA >= startB && startA <= endB) {  
  369.             result = true;  
  370.         } else if (endA >= startB && endA <= endB) {  
  371.             result = true;  
  372.         }  
  373.         return result;  
  374.     }  
  375.   
  376.     private int[] randomXY(Random ran, LinkedList<Integer> listX, LinkedList<Integer> listY, int xItem) {  
  377.         int[] arr = new int[4];  
  378.         arr[IDX_X] = listX.remove(ran.nextInt(listX.size()));  
  379.         arr[IDX_Y] = listY.remove(ran.nextInt(listY.size()));  
  380.         return arr;  
  381.     }  
  382.   
  383.     public void onGlobalLayout() {  
  384.         int tmpW = getWidth();  
  385.         int tmpH = getHeight();  
  386.         if (width != tmpW || height != tmpH) {  
  387.             width = tmpW;  
  388.             height = tmpH;  
  389.             show();  
  390.         }  
  391.     }  
  392.   
  393.     public Vector<String> getKeywords() {  
  394.         return vecKeywords;  
  395.     }  
  396.   
  397.     public void rubKeywords() {  
  398.         vecKeywords.clear();  
  399.     }  
  400.   
  401.     /** 直接清除所有的TextView。在清除之前不會顯示動畫。 */  
  402.     public void rubAllViews() {  
  403.         removeAllViews();  
  404.     }  
  405.   
  406.     public void setOnItemClickListener(OnClickListener listener) {  
  407.         itemClickListener = listener;  
  408.     }  
  409.   
  410.     // public void onDraw(Canvas canvas) {  
  411.     // super.onDraw(canvas);  
  412.     // Paint p = new Paint();  
  413.     // p.setColor(Color.BLACK);  
  414.     // canvas.drawCircle((width >> 1) - 2, (height >> 1) - 2, 4, p);  
  415.     // p.setColor(Color.RED);  
  416.     // }  
  417. }  
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章