【问题标题】:white screen when using runOnUiThread使用 runOnUiThread 时出现白屏
【发布时间】:2014-05-06 10:51:44
【问题描述】:

我正在进行 onTouchListener 的实验。目的是将 FrameLayout 移动到我触摸的任何地方。 第一个版本的代码给了我一个“viewroot$calledfromwrongthreadexception”错误。 所以在第二个版本中,我尝试使用 runOnUiThread 来解决错误。但这样做只会出现白屏。

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

 }

 }

【问题讨论】:

    标签: android ontouchlistener ui-thread background-thread setcontentview


    【解决方案1】:

    onCreate 方法在主 (UI) 线程上运行,您发布一个 Runnable 以在主 (UI) 线程上运行。

    在那个线程中你有一个循环

    while (p_running)
    

    所以这个 while 循环在 UI 线程上无限循环地运行。

    您可以像这样简单地将代码移动到另一个线程

    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();
    

    但仍然存在问题,因为您不断向 UI 线程发布新的 Runnables,这可能会导致 UI 响应非常差

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-06-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多