2013-06-21 28 views
12

我是Android新手,學習如何使用TextSwitcher。 我想知道如何使用TextSwitcher文字動畫。在Android中使用TextSwitcher創建動畫文本

我有一個TextSwitcher和一個按鈕的佈局。 當我點擊按鈕時,TextSwitcher應該切換文本。

我讀到這這裏....

Create Android TextSwitcher with dynamically generated Textview

但我無法得到它的工作。

如何動畫文本,以便當我點擊按鈕時TextSwitcher切換文本。

+0

哪裏出了問題 – Sam

回答

14

TextSwitcher可用於屏幕上的動畫文本。 見詳細Using TextSwitcher In Android博客和所有的內容從博客Using TextSwitcher In Android

我們需要設置IN和OUT動畫拍攝。

  1. 動畫:文字進入屏幕。
  2. 輸出動畫:文字從屏幕出來。

完整的代碼與適當的意見

public class MainActivity extends Activity { 
    private TextSwitcher mSwitcher; 
    Button btnNext; 

    // Array of String to Show In TextSwitcher 
    String textToShow[]={"Main HeadLine","Your Message","New In Technology","New Articles","Business News","What IS New"}; 
    int messageCount=textToShow.length; 
    // to keep current Index of text 
    int currentIndex=-1; 



    @Override 
    protected void onCreate(Bundle savedInstanceState) 
    { 
     super.onCreate(savedInstanceState); 

     setContentView(R.layout.example1_layout); 

     // get The references 
     btnNext=(Button)findViewById(R.id.buttonNext); 
     mSwitcher = (TextSwitcher) findViewById(R.id.textSwitcher); 

     // Set the ViewFactory of the TextSwitcher that will create TextView object when asked 
     mSwitcher.setFactory(new ViewFactory() { 

      public View makeView() { 
       // TODO Auto-generated method stub 
       // create new textView and set the properties like colour, size, gravity etc 
       TextView myText = new TextView(MainActivity.this); 
       myText.setGravity(Gravity.TOP | Gravity.CENTER_HORIZONTAL); 
       myText.setTextSize(36); 
       myText.setTextColor(Color.BLUE); 
       return myText; 
      } 
     }); 

     // Declare the in and out animations and initialize them 
     Animation in = AnimationUtils.loadAnimation(this,android.R.anim.slide_in_left); 
     Animation out = AnimationUtils.loadAnimation(this,android.R.anim.slide_out_right); 

     // set the animation type of textSwitcher 
     mSwitcher.setInAnimation(in); 
     mSwitcher.setOutAnimation(out); 

     // ClickListener for NEXT button 
     // When clicked on Button TextSwitcher will switch between texts 
     // The current Text will go OUT and next text will come in with specified animation 
     btnNext.setOnClickListener(new View.OnClickListener() { 

      public void onClick(View v) { 
       // TODO Auto-generated method stub 
       currentIndex++; 
       // If index reaches maximum reset it 
       if(currentIndex==messageCount) 
        currentIndex=0; 
       mSwitcher.setText(textToShow[currentIndex]); 
      } 
     }); 

    } 
}