Wednesday, June 19, 2013

TextSwitcher in Android

TextSwitcher


A TextSwitcher is a specialized ViewSwitcher that contains only children of type TextView. A TextSwitcher is useful to animate a label on screen. Whenever setText(CharSequence) is called, TextSwitcher animates the current text out and animates the new text in.

Two types animations are required for  for TextSwitcher to switch between the texts.
1: In Animation: with which  Text come in the Screen.
2: Out Animation: with which Text goes out from the Screen.

As you can see in below image that current Text is going OUT and Next Text is Coming In


TextSwitcher



What we Need:

We need to set the in and out Animation type of TextSwitcher  like...
         mSwitcher.setInAnimation(in);
         mSwitcher.setOutAnimation(out);
                    
In this Post I have given 3 Example Demos

In Example 1, I have a TextSwitcher and a button called "NEXT" , when user clickes on NEXT button   TextSwitcher will switch between texts . The current Text will go OUT and next Text will come in with specified Animation.


In Example 2, I have a TextSwitcher ,and two Buttons "START"  and "STOP" , when User clicks on START TextSwitcher automatically start  switching between Text, and when User clicks on STOP TextSwitcher will stop switching the Text , I have implemented it using Threads

TextSwitcher Example 1:


In this Example I have following layout


TextSwitcher



when user clickes on NEXT button   TextSwitcher will switch between texts . The current Text will go OUT and next Text will come in with specified Animation.

example1_layout.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

     <TextSwitcher
            android:layout_marginTop="50dp"
            android:id="@+id/textSwitcher"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_gravity="center_horizontal" />
  
      <Button
            android:id="@+id/buttonNext"
            android:layout_marginTop="150dp"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:text="NEXT"
           />
     
 </LinearLayout>



Text SwitcherExample1Activity.java

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 clolr, size 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]);
                            }
                        });
             
            }

}
       

TextSwitcher Example 2


In this Example  I have following layout



TextSwitcher

I have a TextSwitcher ,and two Buttons "START"  and "STOP" , when User clicks on START TextSwitcher automatically start  switching between Text, and when User clicks on STOP TextSwitcher will stop switching the Text , I have implemented it using Threads

example2_layout.xml


<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

  
      <TextSwitcher
            android:layout_marginTop="50dp"
            android:id="@+id/textSwitcher"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_gravity="center_horizontal" />
     
      <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_marginTop="150dp"
            android:orientation="horizontal">
  
              <Button
                    android:id="@+id/buttonStart"
                    android:layout_weight="1"
                    android:layout_width="fill_parent"
                 android:layout_height="wrap_content"
                 android:text="Start"
                 />
     
              <Button
                    android:id="@+id/buttonStop"
                 android:layout_weight="1"
                 android:layout_width="fill_parent"
                 android:layout_height="wrap_content"
                 android:text="Stop"
                   />
           </LinearLayout>

</LinearLayout>




TextSwitcherExample2Activity.java



public class TextSwitcherExample2Activity  extends Activity
{

           private TextSwitcher mSwitcher;
            Button btnStart,btnStop;
   
            // 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;
            int currentIndex=-1; // to keep current Index

            // Declare in and out Animations
            Animation in,out;
            Context mContext;
           
            private Handler mHandler = new Handler();
       
             // Create a Runnable Instance
            Runnable r=new Runnable() {
                // Override the run Method
                public void run() {
                    // TODO Auto-generated method stub
                    try
                    {
                        // Update the TextSwitcher text
                        updateTextSwitcherText();
                       
                    }
                    finally
                    {
                        mHandler.postDelayed(this, 1000);
                    }
                }
            };
           
          

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

                      
setContentView(R.layout.example2_layout);               
                        mContext=this;
                        btnStart=(Button)findViewById(R.id.buttonStart);
                        btnStop=(Button)findViewById(R.id.buttonStop); 

                        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
                                TextView myText = new TextView(getApplicationContext());
                                myText.setGravity(Gravity.TOP | Gravity.CENTER_HORIZONTAL);
                                myText.setTextSize(36);
                                myText.setTextColor(Color.BLUE);
                                return myText;
                            }
                        });

                        // initialize the in and out  animations
                        in = AnimationUtils.loadAnimation(this,android.R.anim.slide_in_left);
                        out = AnimationUtils.loadAnimation(this,android.R.anim.slide_out_right);
                        mSwitcher.setInAnimation(in);
                        mSwitcher.setOutAnimation(out);

                        mHandler.postDelayed(r, 1000);
                       
                       
                        // Button Start Click Listener
                        btnStart.setOnClickListener(new View.OnClickListener() {
                   
                            public void onClick(View v) {
                               
                                // Start The Text Switcher Animation  
                                mHandler.postDelayed(r,1000);   
                            }
                        });
               
                        // Button Stop Click Listener
                        btnStop.setOnClickListener(new View.OnClickListener() {
                   
                            public void onClick(View v) {
                                  
                                    // Stop the Text Switcher Animation
                                    mHandler.removeCallbacks(r);
                            }
                        });
               
                 }
           
            // method to Update the TextSwitcher Text
            private void updateTextSwitcherText()
            {
                        currentIndex++;
                        if(currentIndex==messageCount)
                            currentIndex=0;
                        mSwitcher.setText(textToShow[currentIndex]);
            }
}

         
You can see Moving Text in following snapshot


TextSwitcher


Other Good Topics

New Advance Topics:
Android ImageSwitcher                    Android TextSwitcher                                Android ViewFlipper
Android Gesture Detector               Handling/Detecting Swap Events                Gradient Drawable
Detecting Missed Calls                    Hide Title Bar                                           GridView Animation

 Beginning With Android
      Android : Introduction                                                              Configuring Eclipse for Android Development
     Creating Your First Android Project                                           Understanding Android Manifest File of your android app

 Advance Android Topics                                                              Customizing Android Views


Working With Layouts                                                                Working With Views

Understanding Layouts in Android                                                   Using Buttons and EditText in Android
Working with Linear Layout (With Example)                                     Using CheckBoxes in Android
Nested Linear Layout (With Example)                                              Using AutoCompleteTextView in Android                                                                                          Grid View
Relative Layout In Android                                                               ListView
Table Layout                                                                                   Android ProgressBar
Frame Layout(With Example)                                                          Customizing ProgressBar
Absolute Layout                                                                             Customizing Radio Buttons
Grid Layout                                                                                    Customizing Checkboxes In Android

Android Components                                                                 Dialogs In Android

Activity In Android                                                                    Working With Alert Dialog
Activity Life Cycle                                                                    Adding Radio Buttons In Dialog
Starting Activity For Result                                                       Adding Check Boxes In Dialog
Sending Data from One Activity to Other in Android                    Creating Customized Dialogs in Android
Returning Result from Activity                                                   Creating Dialog To Collect User Input
Android : Service                                                                     DatePicker and TimePickerDialog
BroadcastReceiver                                                                   Using TimePickerDialog and DatePickerDialog In android

Menus In Android                                                                ListView:
Creating Option Menu                                                               Populating ListView With DataBase
Creating Context Menu In Android                                              Populating ListView with ArrayList
                                                                                               ListView with Custom Adapter

Toast                                                                                      Working With SMS
Customizing Toast In Android                                                       How to Send SMS in Android
Customizing the Display Time of Toast                                        How To Receive SMS
Customizing Toast At Runtime                                                  Accessing Inbox In Android
Adding Image in Toast
Showing Toast for Longer Time


TelephonyManager                                                            Storage: Storing Data In Android
Using Telephony Manager In Android                                          SharedPreferences In Android
                                                                                              Reading and Writing files to Internal Stoarage
Working With Incoming Calls                                             DataBase
How To Handle Incoming Calls in Android                                Working With Database in Android
How to Forward an Incoming Call In Android                            Creating Table In Android
CALL States In Android                                                          Inserting, Deleting and Updating Records In Table in Android


Miscellaneous
Notifications In Android
How To Vibrate The Android Phone
Sending Email In Android
Opening a webpage In Browser
How to Access PhoneBook In Android
Prompt User Input with an AlertDialog





No comments:

Post a Comment