Search code examples
javaandroidmultithreadingcursor

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 ?


Solution

  • 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...);