简体   繁体   中英

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. 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.

You need to use AsyncTask for your database access. In the runInBackground() you need to set your button to show "loading". You could refer to this - 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.

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. You should perform the database operation outside of the UI thread. Read http://developer.android.com/resources/articles/painless-threading.html .

You could use a Handler to notify you when the Db query gets completed and change the text appropriately. For using Handlers, I referred this tutorial

Actually the text is changing, it just hasn't been rendered yet, try to invalidate() the button too. 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

当Db开始加载时将其设置为加载,并在加载停止后更改为“完成”。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM