Settext causing text to flicker irratically

2019-09-10 07:48发布

问题:

I'm making an app which establishes USB communication between an Arduino UNO R3 and an android tablet. Arduino board is sending data correctly and it is even being received by tablet correctly and when tried to display, the text does get printed but with a rather continuous flicker.

class MyThread extends Thread
{
    @Override
    public void run()
    {
        mCallback = new UsbSerialInterface.UsbReadCallback()
        { //Defining a Callback which triggers whenever data is read.
            @Override
            public void onReceivedData(byte[] arg0) //data received in bytes
            {
                String data = null;

                try
                {

                    data = new String(arg0, "UTF-8");
                    handler.post(new newthread(data));                            

                }
                catch (UnsupportedEncodingException e)
                {
                    e.printStackTrace();
                }
            }
        };
    }
}
class newthread implements Runnable
{
    String str1;        

    public newthread(String STR1)
    {            
        str1 = STR1;
    }
    @Override
    public void run()
    {

        DoseRateDisplay = (TextView) findViewById(R.id.DoseRateDisplay);
        if(str1.contains("L"))
        { tv6.append("Health OK"); }
        else
        {
           DoseRateDisplay.settext(str1);
        }
    }
}

I think the reason for flicker can be that the data is incoming too fast. Using Thread.sleep does not help. What can be the possible solution to this problem ? Also, using append instead of settext doesn't cause any flickering problems, but then data gets appended to textview.

回答1:

From my comment: try to check if the text received and the text already in the TextView are equal:

if(!DoseRateDisplay.getText().toString().equals(str1)) {
    DoseRateDisplay.settext(str1);
}