【发布时间】:2011-08-10 04:03:20
【问题描述】:
我想在 android 中更改 UI。
我的主类创建第二个类,然后第二个类调用主类的方法。主类中的方法应该更新 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 崩溃了,因为你不能用另一个线程来改变 UI。如果你想改变 UI 中的某些东西,你应该使用它自己的线程意味着 UI 线程。
标签: java android multithreading