Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Blinking cursor in TextView via Thread

I want to create a blinking cursor in a TextView.. So far i got this:

    myTv = (TextView)findViewById(R.id.myTv);


    //blinking Cursors Thread
    class CursorThread extends Thread 
    {
        public void run()
        {
            while (true) 
            {
                myTv.setText("|");

                try 
                {
                    sleep(1000);
                } 
                catch (InterruptedException e) 
                {}

                myTv.setText(" ");

                try 
                {
                    sleep(1000);
                } 
                catch (InterruptedException e) 
                {}
            }  
        }
    }
    CursorThread cThread = new CursorThread();
    cThread.start();

If i ran this app i get a crash. What m i doing wrong ? Im dont know many things about Threads... Oh and this Thread is an inner class in my MainActivity of course.

Anybody can help ?

like image 850
Adam Varhegyi Avatar asked May 02 '26 20:05

Adam Varhegyi


2 Answers

You must access the UI thread from another thread with the runOnUI method like shown here

runOnUiThread(new Runnable() {
    public void run() {
        keresetTv.setText(" ");
    }
});

or by using a handler.post(new Runnable...);

like image 178
androidu Avatar answered May 05 '26 10:05

androidu


An alternative: subclass TextView and have its onDraw call postInvalidateDelayed() , effecting an invalidate of itself after a number of milliseconds. Track time between calls in onDraw, and flash the cursor appropriately.

like image 34
Julian Fondren Avatar answered May 05 '26 10:05

Julian Fondren