Two ways to implement the Android text Auto-scrolling (marquee) effect [especially so]

Source: Internet
Author: User

Sometimes the marquee effect written in XML does not scroll: The reasons are as follows

In the Android system TextView realizes the marquee effect, must have the following several conditions: 1, android:ellipsize= "marquee" 2, TextView must be shown in a single line, that is, the content must exceed the TextView size 3, TextView to get focus to scroll ( if not, use the custom TextView control to override IsFocused () to return true to the line "method code in the Alwaysmarqueetextview class below", However, the new problem is that the interface has more than one such control display when the dialog after the popup of these custom TextView control will lose focus, the marquee effect becomes "..." in the form of, when the dialog disappear and return to normal) XML code: android:ellipsize= "Marquee", android:singleline= "true" Java Code: Mtvtext.settext ("Hum to the bettering wind Festival Lei Feng Spirit/http orgcent.com/, long, long, long, long and Long data "); Mtvtext.setsingleline (true); Mtvtext.setellipsize (Truncateat.marquee);P s: Textview.sethorizontallyscrolling (TRUE); Allow text to slide horizontally TextView You can also set the scrolling times for the marquee effect, as follows: XML code settings: android:marqueerepeatlimit= "1". 1 represents 1 times, and 1 represents an infinite loop. Java Code settings: Mtvtext.setmarqueerepeatlimit (-1);

Summary of the results of the implementation of the marquee, online more popular there are two, tested can achieve text scrolling effect, the proposed use of the first, because you can better control the text scrolling speed, style, font and other properties, the second method, has not found a control method!

The first type:

Control class: Autoscrolltextview inherited the TextView and made some changes to achieve the width of the judgment, text automatic scrolling and start and stop scrolling and other functions.

Import Android.content.Context;
Import Android.graphics.Canvas;
Import Android.graphics.Paint;
Import Android.os.Parcel;
Import android.os.Parcelable;
Import Android.util.AttributeSet;
Import Android.view.Display;
Import Android.view.View;
Import Android.view.WindowManager;
Import Android.view.View.OnClickListener;
Import Android.widget.TextView;


public class Autoscrolltextview extends TextView implements Onclicklistener {
     Public final static String TAG = AutoScrollTextView.class.getSimpleName ();
   
    private Float textLength = 0f;//text length
     private float viewwidth = 0f;
    private Float step = 0f;//Text's horizontal axis
    private float y = 0f;//The ordinate of the text
    private Float temp_view_plus_text_length = 0.0f;//temporary variable for calculation
     private float temp_view_plus_two_text_length = 0.0f;//temporary variable for calculation
    public Boolean Isstarting = false;//Whether to start scrolling
    private paint paint = null;//drawing style
     Private String Text = "";//text content


Public Autoscrolltextview (Context context) {
Super (context);
Initview ();
}

Public Autoscrolltextview (context context, AttributeSet Attrs) {
Super (context, attrs);
Initview ();
}

Public Autoscrolltextview (context context, AttributeSet attrs, int defstyle) {
Super (context, attrs, Defstyle);
Initview ();
}


private void Initview ()
{
Setonclicklistener (this);
}


public void init (WindowManager windowmanager)
{
Paint = Getpaint ();
Text = GetText (). toString ();
TextLength = Paint.measuretext (text);
Viewwidth = GetWidth ();
if (Viewwidth = = 0)
{
if (WindowManager! = null)
{
Display display = Windowmanager.getdefaultdisplay ();
Viewwidth = Display.getwidth ();
}
}
Step = textLength;
Temp_view_plus_text_length = Viewwidth + textLength;
Temp_view_plus_two_text_length = Viewwidth + textLength * 2;
y = gettextsize () + getpaddingtop ();
}

@Override
Public parcelable onsaveinstancestate ()
{
Parcelable superstate = Super.onsaveinstancestate ();
savedstate ss = new savedstate (superstate);

Ss.step = step;
ss.isstarting = isstarting;

return SS;

}

@Override
public void Onrestoreinstancestate (parcelable state)
{
if (! ( State instanceof savedstate)) {
Super.onrestoreinstancestate (state);
Return
}
savedstate ss = (savedstate) state;
Super.onrestoreinstancestate (Ss.getsuperstate ());

Step = Ss.step;
isstarting = ss.isstarting;

    }
   
    public static class Savedstate extends Basesavedstate {
         public Boolean isstarting = false;
        public Float step = 0.0f;
        savedstate (parcelable superstate) {
             super (superstate);
        }

         @Override
         public void Writetoparcel (Parcel out, int flags) {
             super.writetoparcel (out, flags);
            out.writebooleanarray (New boolean[] {isstarting});
            out.writefloat (step);
        }


        public static final parcelable.creator<savedstate> CREATOR
                = New Parcelable.creator<savedstate> () {
            
            public SavedState[] NewArray ( int size) {
                 return new Savedstate[size];
            }

             @Override
             public savedstate Createfromparcel (Parcel in) {
                 return New SavedState ( in);
            }
        };

        private savedstate (Parcel in) {
             super (in);
            boolean[] b = null;
            in.readbooleanarray (b);
            if (b! = null && b.length > 0)
                isstarting = B[0];
            step = In.readFloat ();
        }
    }

   
    public void Startscroll ()
    {
        isstarting = true;
        invalidate ();
    }
   
   
    public void Stopscroll ()
     {
        isstarting = false;
        invalidate ();
    }
   

@Override
public void OnDraw (canvas canvas) {
Canvas.drawtext (text, Temp_view_plus_text_length-step, y, paint);
if (!isstarting)
{
Return
}
Step + = 0.5;//0.5 is text scrolling speed.
if (Step > Temp_view_plus_two_text_length)
Step = textLength;
Invalidate ();

}

@Override
public void OnClick (View v) {
if (isstarting)
Stopscroll ();
Else
Startscroll ();

}

}

Methods used in XML:

<cn.tigertian.ui.autoscrolltextview

Android:id= "@+id/textviewnotice"
android:layout_height= "30px"

Android:layout_width= "Fill_parent"
android:text= "@string/test_notice_1"

Android:textcolor= "#000"

Android:inputtype= "Text"
Android:background= "#EEE"

Android:textsize= "20px" >

</cn.tigertian.ui.AutoScrollTextView>

How to use the activity:

Start the announcement scroll bar
Autoscrolltextview = (Autoscrolltextview) Findviewbyid (R.id.textviewnotice);
Autoscrolltextview.init (Getwindowmanager ());
Autoscrolltextview.startscroll ();

Note: If you want to change the text content of the marquee or text effect, then after the call to the SetText method, you need to call the Init method, re-initialization and calculation of related parameters.

The second type:

TextView implementation of text scrolling requires the following points: 1. Text length is longer than can be displayed range: Android:singleline= "true" 2. Set scroll to, or display style: android:ellipsize= "marquee" 3. TextView The hidden text is only scrolled when the focus is taken, so you need to create a new class in the package to inherit the TextView. Overriding the IsFocused method, the default behavior of this method is that if TextView gets the focus, the method returns true and loses focus returns false. The marquee effect is also evaluated using this method to determine if the focus is obtained, so the return value is always set to true. The following are transferred from others:Java language: Alwaysmarqueetextview class

Public class Alwaysmarqueetextviewextendstextview{

Public Alwaysmarqueetextview (Contextcontext) {
Super (context);
}

Public Alwaysmarqueetextview (contextcontext,attributesetattrs) {
Super (Context,attrs);
}

Public Alwaysmarqueetextview (contextcontext,attributesetattrs,intdefstyle) {
Super (Context,attrs,defstyle);
}

@Override
Public booleanisFocused () {
return true;
}

Adding such a alwaysmarqueetextview to the layout XML file is something you just learned.

XML Language: Layout.xml <com.examples.alwaysmarqueetextview
Android:id= "@+id/amtv1″
Android:layout_width= "Fill_parent"
android:layout_height= "Wrap_content"
Android:lines= "1″
Android:focusable= "true"
Android:focusableintouchmode= "true"
Android:scrollhorizontally= "true"
android:marqueerepeatlimit= "Marquee_forever"
Android:ellipsize= "Marquee"
Android:background= "@android: Color/transparent"
/>

Ellipsize Property
Sets how the control is displayed when the text is too long. The following values are set: "Start"-the ellipsis is displayed at the beginning; "End"-the ellipsis is displayed at the end; "Middle"-the ellipsis is displayed in the middle; "Marquee"--displayed in the form of a marquee (animation moves Sideways)

Marqueerepeatlimit Property
Sets the number of times to repeat scrolling when ellipsize specifies marquee, which is expressed indefinitely when set to Marquee_forever.

Focusable Property
What you are guessing is whether you can get the focus, and the same focusableintouchmode should be the focus when sliding.

Problem with view combination:

XML Language: Combination View < LinearLayout
xmlns:android = "Http://schemas.android.com/apk/res/android"
Android:orientation = "vertical"
android:gravity = "Center_vertical"
Android:background = "@drawable/f_background"
Android:layout_width = "Fill_parent"
Android:focusable = "true"
Android:layout_height = "50px" >
< TextView
Android:id = "@+id/info_text"
Android:focusable = "true"
Android:layout_width = "Fill_parent"
Android:layout_height = "Wrap_content"
Android:text = "Test Marquee. “
Android:textcolor = "@color/black"
Android:singleline = "true"
Android:ellipsize = "Marquee"
Android:marqueerepeatlimit = "3″
Android:textsize = "18SP"
/>
< TextView
Android:id = "@+id/date_text"
Android:layout_width = "Fill_parent"
Android:layout_height = "Wrap_content"
android:layout_gravity = "Bottom"
Android:textcolor = "@color/gray"
Android:text = "2010/05/28″
Android:textsize = "12SP"
/>
</linearlayout >

The above example of 2 TextView combination as a view, because the set linearlayout for focusable and TextView can not get focus, so that the textview of the marquee effect is not shown, even if you also set TextView android:focusable= "true" is useless. This is the time to use the Addstatesfromchildren property, set this property in LinearLayout,然后设置TextView的focusable="true"就可以了.关于 addStatesFromChildren的说明:

Sets whetherthisViewGroup‘s drawable statesalso include its children‘s drawable states.

 

Two ways to implement the Android text Auto-scrolling (marquee) effect [especially so]

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.