Get delay on UI thread

半世苍凉 提交于 2019-12-19 21:47:30

问题


I'm setting color of a listview item using the following code parent.getChildAt(itemPosition).setBackgroundColor(Color.parseColor("#FF9494"));

This piece of code I'm writing in OnItemClickListener.

After setting the color I want to keep this color for a time of 4 Seconds and then restore the color of the item to its previous(say White).

I tried putting a sleep on the UI thread, but I know that it is not a correct approach.

Can anyone suggest me how to achieve this?


回答1:


    parent.getChildAt(itemPosition).setBackgroundColor(Color.parseColor("#FF9494"));
    // Start new Thread that sets the color back in 4 seconds
    new Thread(new Runnable() {
        @Override
        public void run() {
            SystemClock.sleep(4000); // Sleep 4 seconds
            // Now change the color back. Needs to be done on the UI thread
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    parent.getChildAt(itemPosition).setBackgroundColor(Color.parseColor("#000000")); // use whatever other color you want here
                }
            });
        }
    }).start();



回答2:


The main thread has a looper running within. For this it is possible to schedule a Runnable delayed. Within an OnItemClickListener your code could be as simple as:

@Override
public void onItemClick(AdapterView<?> parent, final View view, int position, long id) {
    view.setBackgroundColor(Color.parseColor("#FF9494"));
    view.postDelayed(new Runnable() {
        @Override
        public void run() {
            view.setBackgroundColor(Color.parseColor("#FFFFFF"));
        }
    }, 4000);
}



回答3:


May be you can try to implement an asyncTask which can then be called from onItemClickListener. The doInBackground method of this asyncTask can contain a sleep method to avoid calling the onPostExecute for a while. In the onPostExecute, you can then reset the color as desired.
If sleep method can't be written in the doInBackground method as I am expecting, then put the sleep method also inside the onPostExecute method before changing the text color.



来源:https://stackoverflow.com/questions/28341760/get-delay-on-ui-thread

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!