how to make digital clock display only hours and minutes - android

I have a digital clock on an activity in my app and I want to display only hours and minutes on it and don't want to display seconds.

import android.content.Context;
import android.database.ContentObserver;
import android.os.Handler;
import android.os.SystemClock;
import android.provider.Settings;
import android.text.format.DateFormat;
import android.util.AttributeSet;
import android.widget.TextView;
import java.util.Calendar;
public class DigitalClock extends TextView {
Calendar mCalendar;
private final static String m24 = "k:mm";
private FormatChangeObserver mFormatChangeObserver;
private Runnable mTicker;
private Handler mHandler;
private boolean mTickerStopped = false;
String mFormat;
public DigitalClock(Context context) {
super(context);
initClock(context);
}
public DigitalClock(Context context, AttributeSet attrs) {
super(context, attrs);
initClock(context);
}
private void initClock(Context context) {
if (mCalendar == null) {
mCalendar = Calendar.getInstance();
}
mFormatChangeObserver = new FormatChangeObserver();
getContext().getContentResolver().registerContentObserver(
Settings.System.CONTENT_URI, true, mFormatChangeObserver);
setFormat();
}
#Override
protected void onAttachedToWindow() {
mTickerStopped = false;
super.onAttachedToWindow();
mHandler = new Handler();
/**
* requests a tick on the next hard-second boundary
*/
mTicker = new Runnable() {
public void run() {
if (mTickerStopped) return;
mCalendar.setTimeInMillis(System.currentTimeMillis());
setText(DateFormat.format(mFormat, mCalendar));
invalidate();
long now = SystemClock.uptimeMillis();
long next = now + (1000 - now % 1000);
mHandler.postAtTime(mTicker, next);
}
};
mTicker.run();
}
#Override
protected void onDetachedFromWindow() {
super.onDetachedFromWindow();
mTickerStopped = true;
}
private void setFormat() {
mFormat = m24;
}
private class FormatChangeObserver extends ContentObserver {
public FormatChangeObserver() {
super(new Handler());
}
#Override
public void onChange(boolean selfChange) {
setFormat();
}
}
}
You can use this custom view. This works with gingerbread also. Change the time format to your liking.(m24)

The system sends a broadcast event at the exact beginning of every minutes based on system clock. The most reliable way is to do it like this :
BroadcastReceiver _broadcastReceiver;
private final SimpleDateFormat _sdfWatchTime = new SimpleDateFormat("HH:mm");
private TextView _tvTime;
#Override
public void onStart() {
super.onStart();
_broadcastReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context ctx, Intent intent) {
if (intent.getAction().compareTo(Intent.ACTION_TIME_TICK) == 0)
_tvTime.setText(_sdfWatchTime.format(new Date()));
}
};
registerReceiver(_broadcastReceiver, new IntentFilter(Intent.ACTION_TIME_TICK));
}
#Override
public void onStop() {
super.onStop();
if (_broadcastReceiver != null)
unregisterReceiver(_broadcastReceiver);
}
Don't forget however to initialize your TextView beforehand (to current system time) since it is likely you will pop your UI in the middle of a minute and the TextView won't be updated until the next minute happens.

Related

Activity doesnt mantain connection to its service after minimalising it

I have a problem with an activity after minimalising. Everything is going ok when i start an activity and press start button. But when i minimalise activity and again maximalize it, it doesnt respond to my buttons and commands. Anybody know what to do? This is my first android app so i dont know what is going on..
here are my classes :
TrackerService
package sk.tuke.smart.makac.services;
import android.app.Service;
import android.content.Intent;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.IBinder;
import android.util.Log;
import java.util.ArrayList;
import java.util.Timer;
import java.util.TimerTask;
public class TrackerService extends Service implements LocationListener {
private Intent commandIntent;
private long duration;
private boolean paused,checkedAfterPause;
private int sportActivity;
private double distance,pace,calories;
private ArrayList<Location> finalPositionList = new ArrayList<Location>();
private LocationManager locationManager;
private static final String TAG = "TrackerService";
#Override
public void onStart(Intent intent, int startId) {
super.onStart(intent, startId);
Log.i(TAG,"onStart intent " +intent.getAction());
commandIntent=intent;
checkedAfterPause=true;
if(intent.getAction() == "sk.tuke.smart.makac.COMMAND_START"){
if(intent.getAction() == "sk.tuke.smart.makac.COMMAND_START") {
duration = 0;
}
new Timer().scheduleAtFixedRate(new TimerTask()
{
#Override
public void run() {
if(!paused){
duration++;
Intent intent1 = new Intent();
intent1.setAction("sk.tuke.smart.makac.TICK");
intent1.putExtra("duration", duration);
intent1.putExtra("distance",distance);
sendBroadcast(intent1);
Log.i(TAG,"" + duration);
}
}
}, 1000, 1000);
}else if (intent.getAction() == "sk.tuke.smart.makac.COMMAND_PAUSE"){
paused=true;
locationManager.removeUpdates(this);
}
if(intent.getAction() == "sk.tuke.smart.makac.COMMAND_CONTINUE"){
paused=false;
checkedAfterPause=false;
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,3000,10,this);
}
}
#Override
public void onCreate() {
super.onCreate();
locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,3000,10,this);
}
#Override
public void onDestroy() {
locationManager.removeUpdates(this);
}
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public void onLocationChanged(Location location) {
finalPositionList.add(location);
Location lastLocation;
double minDistance;
if (finalPositionList.size() != 1 && checkedAfterPause) {
lastLocation = finalPositionList.get(finalPositionList.size() - 2);
minDistance=location.distanceTo(lastLocation);
if(minDistance>=2){
distance += location.distanceTo(lastLocation);
}else{
finalPositionList.remove(finalPositionList.size()-1);
}
}
if(commandIntent.getAction() == "sk.tuke.smart.makac.COMMAND_CONTINUE" && !checkedAfterPause){
Log.i(TAG,"checking distance after pause");
lastLocation = finalPositionList.get(finalPositionList.size() - 2);
minDistance=location.distanceTo(lastLocation);
if(minDistance<=100){
distance += location.distanceTo(lastLocation);
}
checkedAfterPause=true;
}
Log.i(TAG,"locations " + finalPositionList);
Log.i(TAG,"distance = " + distance);
}
#Override
public void onStatusChanged(String s, int i, Bundle bundle) {
}
#Override
public void onProviderEnabled(String s) {
}
#Override
public void onProviderDisabled(String s) {
}
public long getDuration(){
return duration;
}
public double getPace(){
return pace;
}
}
SportsActivity
package sk.tuke.smart.makac;
import android.Manifest;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import sk.tuke.smart.makac.helpers.MainHelper;
import sk.tuke.smart.makac.services.TrackerService;
public class StopwatchActivity extends AppCompatActivity {
private static final int MY_PERMISSIONS_REQUEST_FINE_LOCATION = 111;
private static final String TAG = "StopwatchActivity";
private boolean started;
private boolean running;
private boolean paused=false;
private long duration;
private double distance;
private MainHelper helper;
private TextView durationView,distanceView;
private Button startButton,endButton;
private BroadcastReceiver receiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
if(intent.getAction()=="sk.tuke.smart.makac.TICK"){
duration = intent.getLongExtra("duration",duration);
distance = intent.getDoubleExtra("distance",distance);
durationView.setText(helper.formatDuration(duration));
distanceView.setText(helper.formatDistance(distance));
}
}
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_stopwatch);
IntentFilter intentFilter = new IntentFilter("sk.tuke.smart.makac.TICK");
registerReceiver(receiver,intentFilter);
started=false;
running=false;
helper = new MainHelper();
durationView = findViewById(R.id.textview_stopwatch_duration);
distanceView = findViewById(R.id.textview_stopwatch_distance);
startButton = findViewById(R.id.button_stopwatch_start);
endButton = findViewById(R.id.button_stopwatch_endworkout);
if(!canAccessLocation()){
ActivityCompat.requestPermissions(this,
new String[]{
Manifest.permission.ACCESS_COARSE_LOCATION, Manifest.permission.ACCESS_FINE_LOCATION},
MY_PERMISSIONS_REQUEST_FINE_LOCATION);
}
}
public void toggle(View view){
Intent intent = new Intent(this,TrackerService.class);
started=true;
this.running = !this.running;
if(running && started){
startButton.setText("Stop");
endButton.setVisibility(view.GONE);
if(paused){
intent.setAction("sk.tuke.smart.makac.COMMAND_CONTINUE");
paused=false;
}else
intent.setAction("sk.tuke.smart.makac.COMMAND_START");
}
if(!running && started){
startButton.setText("Continue");
endButton.setVisibility(view.VISIBLE);
intent.setAction("sk.tuke.smart.makac.COMMAND_PAUSE");
paused=true;
}
startService(intent);
}
public void endWorkout(View view){
Intent intent = new Intent(this,TrackerService.class);
intent.setAction("sk.tuke.smart.makac.COMMAND_STOP");
startService(intent);
setContentView(R.layout.activity_workout_detail);
onStop();
}
public void openMaps(View view){
Intent intent = new Intent(StopwatchActivity.this, MapsActivity.class);
startActivity(intent);
}
#Override
protected void onStart() {
super.onStart();
}
#Override
protected void onStop() {
super.onStop();
Intent intent= new Intent(this,TrackerService.class);
stopService(intent);
}
private boolean hasPermission(String perm) {
return(PackageManager.PERMISSION_GRANTED==checkSelfPermission(perm));
}
private boolean canAccessLocation() {
return(hasPermission(Manifest.permission.ACCESS_FINE_LOCATION));
}
}
You aren't creating a connection to the service. You're only starting it, not binding it. So there's no connection to maintain.
It looks like you're trying to do quasi-binding via actions. Don't do that, properly bind the service and avoid a whole raft of problems like this.

Is there any clock view in android whose time can be set in activity

I am actually searching for an android clock view whose time can be set in the activity and then it will start working from that setted time.I saw the TextClock view but it seemed that only the timezone can be set.Can anyone help me?
Use this class, might help you, You can change date time whatever you want
import android.content.Context;
import android.database.ContentObserver;
import android.os.Handler;
import android.os.SystemClock;
import android.provider.Settings;
import android.support.v7.widget.AppCompatTextView;
import android.text.format.DateFormat;
import android.util.AttributeSet;
import java.util.Calendar;
public class DigitalClock extends AppCompatTextView {
Calendar mCalendar;
private FormatChangeObserver mFormatChangeObserver;
private Runnable mTicker;
private Handler mHandler;
private boolean mTickerStopped = false;
String mFormat;
public DigitalClock(Context context) {
super(context);
initClock();
}
public DigitalClock(Context context, AttributeSet attrs) {
super(context, attrs);
initClock();
}
private void initClock() {
if (mCalendar == null) {
mCalendar = Calendar.getInstance();
}
}
#Override
protected void onAttachedToWindow() {
mTickerStopped = false;
super.onAttachedToWindow();
mFormatChangeObserver = new FormatChangeObserver();
getContext().getContentResolver().registerContentObserver(
Settings.System.CONTENT_URI, true, mFormatChangeObserver);
setFormat();
mHandler = new Handler();
mTicker = new Runnable() {
public void run() {
if (mTickerStopped) return;
mCalendar.setTimeInMillis(System.currentTimeMillis());
setText(DateFormat.format(mFormat, mCalendar));
invalidate();
long now = SystemClock.uptimeMillis();
long next = now + (1000 - now % 1000);
mHandler.postAtTime(mTicker, next);
}
};
mTicker.run();
}
#Override
protected void onDetachedFromWindow() {
super.onDetachedFromWindow();
mTickerStopped = true;
getContext().getContentResolver().unregisterContentObserver(
mFormatChangeObserver);
}
private void setFormat() {
mFormat = "dd MMM yy , hh:mm ss a ";
}
private class FormatChangeObserver extends ContentObserver {
public FormatChangeObserver() {
super(new Handler());
}
#Override
public void onChange(boolean selfChange) {
setFormat();
}
}
#Override
public CharSequence getAccessibilityClassName() {
//noinspection deprecation
return DigitalClock.class.getName();
}
}

Android app running after locking screen

Hello I am new to android programming. I am writing an app for school and I need to save Accelerometer data to a txt file.
The problem is that when I lock screen or turn screen saving on, the data recording stops.
Can you please give me advice ?
Here is my code:
package emzet.data2text;
import android.app.Activity;
import android.content.Context;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.Bundle;
import android.os.Environment;
import android.os.PowerManager;
import android.view.View;
import android.widget.Button;
import java.io.FileWriter;
import java.io.IOException;
import java.text.SimpleDateFormat;
public class MainActivity extends Activity implements SensorEventListener {
private SensorManager sensorManager;
private Sensor accelerometer;
private FileWriter writer;
private Button btnStart, btnStop;
String root = Environment.getExternalStorageDirectory().toString();
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnStart = (Button) findViewById(R.id.btnStart);
btnStop = (Button) findViewById(R.id.btnStop);
btnStart.setEnabled(true);
btnStop.setEnabled(true);
//PowerManager mgr = (PowerManager)this.getSystemService(Context.POWER_SERVICE);
//PowerManager.WakeLock wakeLock = mgr.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK | PowerManager.ACQUIRE_CAUSES_WAKEUP, "MyWakeLock");
sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
accelerometer = sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
}
public void onStartClick(View view) {
sensorManager.registerListener(this, accelerometer, SensorManager.SENSOR_DELAY_NORMAL);
btnStop.setEnabled(true);
btnStart.setEnabled(false);
}
public void onStopClick(View view) {
sensorManager.unregisterListener(this);
btnStart.setEnabled(true);
btnStop.setEnabled(false);
}
protected void onResume() {
super.onResume();
try {
writer = new FileWriter(root + "/acc2txt-file.txt",true);
} catch (IOException e) {
e.printStackTrace();
}
}
protected void onPause() {
super.onPause();
if(writer != null) {
try {
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
#Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
#Override
public void onSensorChanged(SensorEvent event) {
float x = event.values[0];
float y = event.values[1];
float z = event.values[2];
SimpleDateFormat time = new SimpleDateFormat("HH:mm:ss:SSS");
String s = time.format(new java.util.Date());
try {
writer.write(s+"\t"+x+"\t"+y+"\t"+z+"\n");
} catch (IOException e) {
e.printStackTrace();
}
}
}
if you want to save data in app stop as well, you can write a service with START_STICKY option , then the service stays active even if the app is killed. Here is example of STICKY Service, it is easy and would fit your needs example 1 example 2
public class MyService extends Service {
protected String messageData = null;
public static final int MSG_REGISTER_CLIENT = 1;
public static final int MSG_UNREGISTER_CLIENT = 2;
public static final int MSG_CUSTOM_TYPE = 3;
#Override public void onCreate() {
super.onCreate();
MyServiceRunningBackground();
running = true;
}
#Override public int onStartCommand(Intent intent, int flags, int startId) {
return START_STICKY;
}
#Override
public IBinder onBind(Intent intent) {
//TODO for communication return IBinder implementation
return null;
}
#Override public boolean onUnbind(Intent intent) {
return super.onUnbind(intent);
}
#Override public void onRebind(Intent intent) {
super.onRebind(intent);
}
#Override public void onDestroy() {
super.onDestroy();
running = false;
}
private void MyServiceRunningBackground() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT)
{
final int restartAlarmInterval = 6000;
final int resetAlarmTimer = 2*1000;
final Intent restartIntent = new Intent(this, esService.class);
restartIntent.putExtra("ALARM_RESTART_SERVICE_DIED", true);
final AlarmManager alarmMgr = (AlarmManager)getSystemService(Context.ALARM_SERVICE);
Handler restartServiceHandler = new Handler()
{
#Override
public void handleMessage(Message msg) {
PendingIntent pintent = PendingIntent.getService(getApplicationContext(), 0, restartIntent, 0);
alarmMgr.set(AlarmManager.ELAPSED_REALTIME, SystemClock.elapsedRealtime() + restartAlarmInterval, pintent);
sendEmptyMessageDelayed(0, resetAlarmTimer);
}
};
restartServiceHandler.sendEmptyMessageDelayed(0, 0);
}
}
private static final String TAG = "MyService";
}
create this new service and do what work you want to perform in your case saving data in background of your app, even if you app is killed, just start this service like you open new intent in your onCreate of activity. After that this service will be active even user kills app. Start this service like this
Intent intent = new Intent(MyActivity.this, MyService.class);
startService(intent);
I hope I am clear

Starting new activity triggered by boolean in GameThread (android)

I am making a "Defend the castle" style android application. The game is complete, however I just need help closing my surfaceview and starting a new activity for when the the player has lost the game.
The condition for losing the game is just a boolean variable in my GameThread class. The variable is called "lost" and is by default set to false. When the life of the castle drops below 1, lost is set to true and a sound effect plays.
Ideally, I would like to stop the currently looping sound effects and open a new activity (which is already made and working) upon lost=true.
The main activity is as follows:
import android.app.Activity;
import android.content.Intent;
import android.content.res.Configuration;
import android.os.Bundle;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
public class MainActivity extends Activity {
Button btn_startGame;
Activity activity;
GameView mGameView;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
activity = this;
setContentView(R.layout.main);
btn_startGame = (Button) findViewById(R.id.btnStartGame);
btn_startGame.setOnClickListener(new OnClickListener() {
//#Override
public void onClick(View v) {
mGameView = new GameView(activity);
setContentView(mGameView);
mGameView.mThread.doStart();
}
});
}
#Override
public boolean onTouchEvent(MotionEvent event) {
try {
mGameView.mThread.onTouch(event);
} catch(Exception e) {}
return true;
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
// ignore orientation/keyboard change
super.onConfigurationChanged(newConfig);
}
}
The surfaceview is created in this class called GameView:
import android.content.Context;
import android.content.Intent;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.SurfaceHolder.Callback;
public class GameView extends SurfaceView implements Callback {
Context mContext;
GameThread mThread;
public GameView(Context context) {
super(context);
this.mContext = context;
getHolder().addCallback(this);
mThread = new GameThread(getHolder(), mContext, new Handler() {
#Override
public void handleMessage(Message m) {
// Use for pushing back messages.
}
});
setFocusable(true);
}
//#Override
public void surfaceChanged(SurfaceHolder holder, int format, int width,
int height) {
Log.d(this.getClass().toString(), "in SurfaceChanged()");
}
//#Override
public void surfaceCreated(SurfaceHolder holder) {
Log.d(this.getClass().toString(), "in SurfaceCreated()");
mThread.running = true;
mThread.start();
}
//#Override
public void surfaceDestroyed(SurfaceHolder holder) {
Log.d(this.getClass().toString(), "in SurfaceDestroyed()");
boolean retry = true;
mThread.running = false;
while (retry) {
try {
mThread.join();
retry = false;
} catch (InterruptedException e) {
}
GameThread.music.stop();
GameThread.groan1.stop();
GameThread.groan2.stop();
GameThread.walk.stop();
GameThread.music.release();
GameThread.groan1.release();
GameThread.groan2.release();
GameThread.walk.release();
GameThread.shoot.release();
}
}
}
The GameThread class contains all of the drawing, the logic and all a run method (below).
#Override
public void run() {
// check if condition here
if(lost){
mContext.runOnUiThread(new Runnable() {
#Override
public void run() {
//start Activity here
Intent intent = new Intent(mContext, LoseActivity.class);
mContext.startActivity(intent);
}
});
}
else{
if (running == true) {
while (running) {
Canvas c = null;
try {
c = mHolder.lockCanvas();
if (width == 0) {
width = c.getWidth();
height = c.getHeight();
player.x = 50;
player.y = 45;
}
synchronized (mHolder) {
long now = System.currentTimeMillis();
update();
draw(c);
ifps++;
if (now > (mLastTime + 1000)) {
mLastTime = now;
fps = ifps;
ifps = 0;
}
}
} finally {
if (c != null) {
mHolder.unlockCanvasAndPost(c);
}
}
}
}
}
The activity that I want to start is called LoseActivity.class. Thank you in advance for any and all help. If anybody needs any further code/explanations, I will be more than happy to post it.
Use runOnUiThread for starting Activity from Thread as:
Change your main Activity as:
public class MainActivity extends Activity {
Button btn_startGame;
Activity activity;
GameView mGameView;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
activity = this;
setContentView(R.layout.main);
btn_startGame = (Button) findViewById(R.id.btnStartGame);
btn_startGame.setOnClickListener(new OnClickListener() {
//#Override
public void onClick(View v) {
mGameView = new GameView(activity,MainActivity.this);
setContentView(mGameView);
mGameView.mThread.doStart();
}
});
}
///your code.....
Change your GameView class as:
public class GameView extends SurfaceView implements Callback {
Context mContext;
Activity contextx;
GameThread mThread;
public GameView(Context context,Activity contextx) {
super(context);
this.mContext = context;
this.contextx=contextx;
getHolder().addCallback(this);
mThread = new GameThread(getHolder(), mContext, new Handler() {
#Override
public void handleMessage(Message m) {
// Use for pushing back messages.
}
});
setFocusable(true);
}
//your code here..........
#Override
public void run() {
// check if condition here
if(lost){
contextx.runOnUiThread(new Runnable() {
#Override
public void run() {
//start Activity here
Intent intent = new Intent(contextx, LoseActivity.class);
contextx.startActivity(intent);
}
});
}
else{
//your code here.........

Remove seconds and AM/PM from Digital clock widget

I want to remove the seconds and AM/PM indication from the digital clock widget but I don't know how to do this.
It is hard-coded in the DigitalClock class, so you can't change it programatically. The only way to change it is to re-implement DigitalClock widget. Yo can get source code from here.
You need to copy this code in your project, rename it like "MyDigitalClock" and use this one as your widget. As you will see in the implementation, there are two variables you should focus on to get what you want:
private final static String m12 = "h:mm:ss aa";
private final static String m24 = "k:mm:ss";
ss represents seconds and aa represents am/pm.
You could use addTextChangedListener() and then take out the seconds and AM/PM in afterTextChanged(). This example just removes the seconds:
DigitalClock dc = (DigitalClock) findViewById(R.id.currentTime);
dc.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
}
#Override
public void afterTextChanged(Editable s) {
if (s.charAt(4) == ':') {
s.delete(4, 7);
} else if (s.charAt(5) == ':') {
s.delete(5, 8);
}
}
});
Let me little extend and refresh perfect answer from Erol.
Actually you need add one file to your project and update xml layout.
Sample could be taken from here: /frameworks/base/core/java/android/widget/DigitalClock.java
Adapted DigitalClock.java:
import android.content.Context;
import android.database.ContentObserver;
import android.os.Handler;
import android.os.SystemClock;
import android.provider.Settings;
import android.text.format.DateFormat;
import android.util.AttributeSet;
import android.widget.TextView;
import java.text.SimpleDateFormat;
import java.util.Calendar;
/**
* Like AnalogClock, but digital. Shows seconds.
*
* #deprecated It is recommended you use {#link TextClock} instead.
*/
#Deprecated
public class DigitalClock extends TextView {
// FIXME: implement separate views for hours/minutes/seconds, so
// proportional fonts don't shake rendering
Calendar mCalendar;
#SuppressWarnings("FieldCanBeLocal") // We must keep a reference to this observer
private FormatChangeObserver mFormatChangeObserver;
private Runnable mTicker;
private Handler mHandler;
private boolean mTickerStopped = false;
java.text.DateFormat mFormat;
public DigitalClock(Context context) {
super(context);
initClock();
}
public DigitalClock(Context context, AttributeSet attrs) {
super(context, attrs);
initClock();
}
private void initClock() {
if (mCalendar == null) {
mCalendar = Calendar.getInstance();
}
mFormatChangeObserver = new FormatChangeObserver();
getContext().getContentResolver().registerContentObserver(
Settings.System.CONTENT_URI, true, mFormatChangeObserver);
setFormat();
}
#Override
protected void onAttachedToWindow() {
mTickerStopped = false;
super.onAttachedToWindow();
mHandler = new Handler();
/**
* requests a tick on the next hard-second boundary
*/
mTicker = new Runnable() {
public void run() {
if (mTickerStopped) return;
mCalendar.setTimeInMillis(System.currentTimeMillis());
// setText(DateFormat.format(mFormat, mCalendar));
setText(mFormat.format(mCalendar.getTime()));
invalidate();
long now = SystemClock.uptimeMillis();
long next = now + (1000 - now % 1000);
mHandler.postAtTime(mTicker, next);
}
};
mTicker.run();
}
#Override
protected void onDetachedFromWindow() {
super.onDetachedFromWindow();
mTickerStopped = true;
}
private void setFormat() {
// mFormat = DateFormat.getTimeFormatString(getContext()); //<== ORIGINAL
// mFormat = DateFormat.getTimeFormat(getContext()); //<== Fixed with PM
// mFormat = new SimpleDateFormat("hh:mm a");
mFormat = new SimpleDateFormat("h:mm"); //<== Your variant
}
private class FormatChangeObserver extends ContentObserver {
public FormatChangeObserver() {
super(new Handler());
}
#Override
public void onChange(boolean selfChange) {
setFormat();
}
}
#Override
public CharSequence getAccessibilityClassName() {
//noinspection deprecation
return DigitalClock.class.getName();
}
}
layout.xml:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".HomeActivity" >
<HERE_YOUR_PACKAGE_NAME.DigitalClock
android:id="#+id/digitalClock"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#android:color/background_light"
android:layout_centerInParent="true"
android:textSize="130dp"/>
</RelativeLayout>
Result:

Categories

Resources