[英]How to execute one line of code before the rest? Changing text on a button
There's a button in my program that, when clicked, accesses a huge database and takes a second or two to do that, and then disappeaars. 我的程序中有一个按钮,当单击该按钮时,它会访问一个巨大的数据库并花一两秒钟来完成该操作,然后消失。 During that waiting time, I would like the button's text to change to "LOADING..." or something.
在这段等待时间内,我希望按钮的文本更改为“ LOADING ...”或其他内容。 I tried
我试过了
myButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
myButton.setText("LOADING...");
//then do other stuff
}
but of course lines of code aren't executed sequentially like that, so the text doesn't show up (or, shows up so quickly before disappearing that it isn't noticeable). 但是当然,代码行不会像这样顺序执行,因此文本不会显示出来(或者在消失之前显示得太快了,以至于不明显)。 Is there a simple way to do this?
有没有简单的方法可以做到这一点? The only thing that comes to mind is using a Timer but (1) I'm not really sure how and (2) that seems overly complicated for just one simple line of code like that.
唯一想到的是使用计时器,但(1)我不太确定如何使用(2)对于仅一行这样的简单代码来说,它似乎过于复杂。
You need to use AsyncTask for your database access. 您需要使用AsyncTask进行数据库访问。 In the runInBackground() you need to set your button to show "loading".
在runInBackground()中,您需要设置按钮以显示“正在加载”。 You could refer to this - http://developer.android.com/reference/android/os/AsyncTask.html
您可以参考此-http://developer.android.com/reference/android/os/AsyncTask.html
http://www.vogella.de/articles/AndroidPerformance/article.html#concurrency_asynchtask is also a really good tutorial to help you with what you are trying to do. http://www.vogella.de/articles/AndroidPerformance/article.html#concurrency_asynchtask也是一个非常不错的教程,可以帮助您完成尝试的工作。
The problem is that everything is done on the UI thread, and the long database access blocks the UI thread and prevents the "Loading..." text to be displayed. 问题是,所有操作都在UI线程上完成,并且长时间的数据库访问会阻塞UI线程并阻止显示“正在加载...”文本。 You should perform the database operation outside of the UI thread.
您应该在UI线程之外执行数据库操作。 Read http://developer.android.com/resources/articles/painless-threading.html .
阅读http://developer.android.com/resources/articles/painless-threading.html 。
Actually the text is changing, it just hasn't been rendered yet, try to invalidate()
the button too. 实际上,文本正在更改,只是尚未呈现,请尝试也
invalidate()
按钮invalidate()
。 You can also just test it out by removing the long process after the button click. 您也可以通过单击按钮后删除冗长的过程来对其进行测试。 Also if you have a long process make sure its not on the main thread and possibly use a ProgressDialog
另外,如果您的过程很长,请确保其不在主线程上,并可能使用ProgressDialog
当Db开始加载时将其设置为加载,并在加载停止后更改为“完成”。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.