Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get delay on UI thread

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?

like image 555
prince Avatar asked Dec 24 '22 23:12

prince


2 Answers

    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();
like image 198
David Wasser Avatar answered Jan 11 '23 06:01

David Wasser


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);
}
like image 31
tynn Avatar answered Jan 11 '23 04:01

tynn