Runnable to be run every second only runs once in Fragment onCreateView()
Posted
by
jul
on Stack Overflow
See other posts from Stack Overflow
or by jul
Published on 2012-03-26T17:26:02Z
Indexed on
2012/03/26
17:29 UTC
Read the original article
Hit count: 254
I'm trying to update the time in a TextView
with a Runnable
supposed to be run every second.
The Runnable
is started from a Fragment
's onCreateView()
, but it's only executed once.
Anybody can help?
Thanks
public class MyFragment extends Fragment {
Calendar mCalendar;
private Runnable mTicker;
private Handler mHandler;
TextView mClock;
String mFormat;
private boolean mClockStopped = false;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
RelativeLayout view = (RelativeLayout) inflater.inflate(R.layout.meteo_widget, container, false);
/*
* Clock (from DigitalClock widget source)
*/
mClock = (TextView) view.findViewById(R.id.clock);
mCalendar = Calendar.getInstance();
mHandler = new Handler();
mTicker = new Runnable() {
public void run() {
if(mClockStopped) return;
mCalendar.setTimeInMillis(System.currentTimeMillis());
mClock.setText(DateFormat.format("hh:mm:ss", mCalendar));
mClock.invalidate();
long now = SystemClock.uptimeMillis();
long next = now + (1000 - now % 1000);
mHandler.postAtTime(mTicker, next);
}
};
mTicker.run();
return view;
}
@Override
public void onResume()
{
super.onResume();
mClockStopped = true;
}
@Override
public void onPause()
{
mClockStopped = false;
super.onPause();
}
}
© Stack Overflow or respective owner