Get delay on UI thread

这一生的挚爱 提交于 2019-12-01 19:43:54
    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();

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);
}

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.

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