1.如果是同一个线程(或者是主线程)里,可以直接进行UI内容的更新,如果是两个不同的线程,更新则会报错,可以用Handler+Runnable来进行不同线程的UI更新
报错代码(报错内容:ERROR/AndroidRuntime(785): android.view.ViewRoot$CalledFromWrongThreadException: Only the original thread that created a view hierarchy can touch its views.):
public class MainActivity extends Activity
{
private TextView tvInfo = null;
private Button btnClick = null;
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
tvInfo = (TextView)findViewById(R.id.tv01);
btnClick = (Button)findViewById(R.id.btnClick);
btnClick.setOnClickListener(new OnClickListener()
{
@Override
public void onClick(View v)
{
new Thread(run).start();
}
});
}
Runnable run = new Runnable()
{
@Override
public void run()
{
tvInfo.setText("kelei");
}
};
}
正确代码1:因为是同一个线程(主线成,所以能直接更改UI上的内容)
public class MainActivity extends Activity
{
private TextView tvInfo = null;
private Button btnClick = null;
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
tvInfo = (TextView) findViewById(R.id.tv01);
btnClick = (Button) findViewById(R.id.btnClick);
btnClick.setOnClickListener(new OnClickListener()
{
@Override
public void onClick(View v)
{
tvInfo.setText("kelei");
}
});
}
}
正确代码2(使用Handler+Runnable):
public class MainActivity extends Activity
{
private TextView tvInfo = null;
private Button btnClick = null;
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
tvInfo = (TextView) findViewById(R.id.tv01);
btnClick = (Button) findViewById(R.id.btnClick);
btnClick.setOnClickListener(new OnClickListener()
{
@Override
public void onClick(View v)
{
Handler handler = new Handler();
handler.post(run);
}
});
}
Runnable run = new Runnable()
{
@Override
public void run()
{
// TODO Auto-generated method stub
tvInfo.setText("kelei");
}
};
}