在Android中运行时更新视图
这个例子非常简单:我想通过显示文本(canvas.drawText())让用户知道应用程序正在做什么。然后,我的第一条消息出现,但不是其他消息。我的意思是,我有一个“setText”方法,但它没有更新。
onCreate(Bundle bundle) {
super.onCreate(bundle);
setContentView(splash); // splash is the view class
loadResources();
splash.setText("this");
boundWebService();
splash.setText("that"):
etc();
splash.setText("so on");
}
视图的文本绘图只需在onDraw();中执行drawText,因此setText会更改文本但不会显示它。
有人建议我用SurfaceView替换视图,但是对于几个更新来说会有很多麻烦,所以...我怎么能在运行时以动态更新视图?
它应该很简单,只显示2秒的文本,然后主线程做他的东西,然后更新文本...
谢谢!
更新:
我尝试实现handler.onPost(),但是又重复了同样的故事。我给你看一下代码:
public class ThreadViewTestActivity extends Activity {
Thread t;
Splash splash;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
splash = new Splash(this);
t = new Thread(splash);
t.start();
splash.setTextow("OA");
try { Thread.sleep(4000); } catch (InterruptedException e) { }
splash.setTextow("LALA");
}
}
和:
public class Splash implements Runnable {
Activity activity;
final Handler myHandler = new Handler();
public Splash(Activity activity) {
this.activity=activity;
}
@Override
public void run() {
// TODO Auto-generated method stub
}
public synchronized void setTextow(final String textow) {
// Wrap DownloadTask into another Runnable to track the statistics
myHandler.post(new Runnable() {
@Override
public void run() {
TextView t = (TextView)activity.findViewById(R.id.testo);
t.setText(textow);
t.invalidate();
}
});
}
}
虽然splash在其他线程中,我在主线程上休眠,我使用处理程序来管理UI和一切,它不会改变一件事,它只显示最后一次更新。
没有找到相关结果
已邀请:
3 个回复
喷乡顾沥沪
来更新UI。有关其他但可能相关的示例,请参阅http://developer.android.com/reference/android/widget/ProgressBar.html。 另见这个答案,特别是第一段: 问题很可能是你 正在运行启动画面(有些 像ProgressDialog这样的Dialog 我假设)与所有人在同一个线程中 正在完成的工作。这将保持 从中看到的启动画面 正在更新,这可以保持它 甚至可以显示在屏幕上。 你需要显示启动画面, 启动AsyncTask的实例 去下载所有数据,然后隐藏 任务完成后的启动画面 完成。 更新(基于您的更新和评论):除了创建活动的线程之外,您不应该更新任何线程中的UI。为什么不能在后台线程中加载资源?
细屠截殴些
在应用程序的主UI线程上执行,因此在您离开之前不会更新UI。基本上,您需要一个线程来执行长时间运行的任务和一些将更新推送到UI的机制。 最常用的方法是扩展AsyncTask,请参阅此链接以获取更多信息
浩挎