我想更改android中的UI。從android中的另一個線程更新ui
我的主類做了第二類,然後第二類調用主類中的main.method方法應該更新UI,但運行時程序崩潰。
我該怎麼辦?
我的主類:
public class FileObserverActivity extends Activity
{
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
tv = (TextView) findViewById(R.id.textView1);
tv.setText("new world");
MyFileObserver myFileObserver = new MyFileObserver("/sdcard/", this);
myFileObserver.startWatching();
}
String mySTR = "";
TextView tv ;
public void event(String absolutePath,String path,int event)
{
mySTR = absolutePath+path+"\t"+event;
tv.setText(mySTR); // program crash here!
}
}
和我的第二類:
public class MyFileObserver extends FileObserver
{
public String absolutePath;
FileObserverActivity fileobserveractivity;
public MyFileObserver(String path,FileObserverActivity foa)
{
super(path, FileObserver.ALL_EVENTS);
absolutePath = path;
fileobserveractivity = foa;
}
@Override
public void onEvent(int event, String path)
{
if (path == null)
{
return;
}
else if(event!=0)
{
fileobserveractivity.event(absolutePath, path, event);
}
else
{
return;
}
}
}
崩潰的任何日誌? – ania
@ania它崩潰了,因爲你不能改變另一個線程的UI。如果你想改變UI中的某些東西,你應該使用它自己的線程意味着UI線程。 –