Pastebin launched a little side project called VERYVIRAL.com, check it out ;-) Want more features on Pastebin? Sign Up, it's FREE!
Guest

Untitled

By: a guest on Apr 17th, 2012  |  syntax: None  |  size: 1.47 KB  |  views: 30  |  expires: Never
download  |  raw  |  embed  |  report abuse  |  print
Text below is selected. Please press Ctrl+C to copy to your clipboard. (⌘+C on Mac)
  1. Runnable to be run every second only runs once in Fragment onCreateView()
  2. public class MyFragment extends Fragment {
  3.  
  4.     Calendar mCalendar;
  5.  
  6.     private Runnable mTicker;
  7.     private Handler mHandler;
  8.  
  9.     TextView mClock;
  10.  
  11.     String mFormat;
  12.  
  13.     private boolean mClockStopped = false;
  14.  
  15.     @Override
  16.     public View onCreateView(LayoutInflater inflater, ViewGroup container,
  17.             Bundle savedInstanceState) {
  18.  
  19.         RelativeLayout view = (RelativeLayout) inflater.inflate(R.layout.meteo_widget, container, false);
  20.  
  21.         /*
  22.          * Clock (from DigitalClock widget source)
  23.          */
  24.  
  25.         mClock = (TextView) view.findViewById(R.id.clock);
  26.  
  27.         mCalendar = Calendar.getInstance();
  28.  
  29.         mHandler = new Handler();
  30.  
  31.         mTicker = new Runnable() {
  32.             public void run() {
  33.                 if(mClockStopped) return;
  34.                 mCalendar.setTimeInMillis(System.currentTimeMillis());
  35.                 mClock.setText(DateFormat.format("hh:mm:ss", mCalendar));
  36.                 mClock.invalidate();
  37.                 long now = SystemClock.uptimeMillis();
  38.                 long next = now + (1000 - now % 1000);
  39.                 mHandler.postAtTime(mTicker, next);
  40.             }
  41.         };
  42.         mTicker.run();
  43.  
  44.         return view;
  45.     }
  46.  
  47.     @Override
  48.     public void onResume()
  49.     {
  50.         super.onResume();
  51.         mClockStopped = true;
  52.     }
  53.  
  54.     @Override
  55.     public void onPause()
  56.     {
  57.         mClockStopped = false;        
  58.         super.onPause();
  59.     }
  60.  
  61. }
clone this paste RAW Paste Data