Search code examples
androidontouchlistenerui-threadbackground-threadsetcontentview

white screen when using runOnUiThread


I am having an experiment of onTouchListener. The aim is to move the FrameLayout to wherever I touch. The 1st version of code gives me a “viewroot$calledfromwrongthreadexception” error. So in the 2nd version, I try to use runOnUiThread to solve the error. But doing so, only gives a white screen.

public class MainActivity extends Activity implements Runnable, OnTouchListener{

private int x,y;
private boolean p_running = false;
private FrameLayout mFrame;

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

        setContentView(R.layout.activity_main);

    mFrame=(FrameLayout) findViewById(R.id.frameLayout1);
    mFrame.setOnTouchListener(this);
    p_running = true;

    runOnUiThread(new Thread(new Runnable(){
            @Override
            public void run(){
                while (p_running){
                mFrame.setPadding(x,y,0,0);
                }
            }
            }));

}

@Override 
public boolean onTouch(View v, MotionEvent event){

    x = (int)event.getX();
    y = (int)event.getY();

    return true;
} 

 @Override
 public void run() {
// TODO Auto-generated method stub

 }

 }

Solution

  • The onCreate method runs on the main (UI) thread and your posting a Runnable to run on the main (UI) thread.

    In that thread you have a loop with

    while (p_running)
    

    so this while loop is running on the UI thread in an infinite loop.

    You could simply move that code to another Thread like so

    Thread t = new Thread (){
    
        @Override
        public void run(){
            while (p_running){
                runOnUiThread(new Runnable(){
    
                    @Override
                    public void run(){
                        mFrame.setPadding(x,y,0,0);
                    }
    
                 });
            }
        }
    });
    t.start();
    

    but there are still issues with that as you are constantly posting new Runnables to the UI thread which will probably result in very poor UI response