Reformat code

pull/30/head
Alinson S. Xavier 10 years ago
parent 1ee3fc79f0
commit c8de4e13f9

@ -21,40 +21,40 @@ import android.graphics.Color;
public class ColorHelper
{
public static final int[] palette =
{
Color.parseColor("#D32F2F"), // red
{
Color.parseColor("#D32F2F"), // red
Color.parseColor("#E64A19"), // orange
Color.parseColor("#F9A825"), // yellow
Color.parseColor("#F9A825"), // yellow
Color.parseColor("#AFB42B"), // light green
Color.parseColor("#388E3C"), // dark green
Color.parseColor("#388E3C"), // dark green
Color.parseColor("#00897B"), // teal
Color.parseColor("#00ACC1"), // cyan
Color.parseColor("#00ACC1"), // cyan
Color.parseColor("#039BE5"), // blue
Color.parseColor("#5E35B1"), // deep purple
Color.parseColor("#5E35B1"), // deep purple
Color.parseColor("#8E24AA"), // purple
Color.parseColor("#D81B60"), // pink
Color.parseColor("#D81B60"), // pink
Color.parseColor("#303030"), // dark grey
Color.parseColor("#aaaaaa") // light grey
};
Color.parseColor("#aaaaaa") // light grey
};
public static int mixColors(int color1, int color2, float amount)
{
final byte ALPHA_CHANNEL = 24;
final byte RED_CHANNEL = 16;
final byte GREEN_CHANNEL = 8;
final byte BLUE_CHANNEL = 0;
{
final byte ALPHA_CHANNEL = 24;
final byte RED_CHANNEL = 16;
final byte GREEN_CHANNEL = 8;
final byte BLUE_CHANNEL = 0;
final float inverseAmount = 1.0f - amount;
final float inverseAmount = 1.0f - amount;
int a = ((int) (((float) (color1 >> ALPHA_CHANNEL & 0xff) * amount) +
((float) (color2 >> ALPHA_CHANNEL & 0xff) * inverseAmount))) & 0xff;
int r = ((int) (((float) (color1 >> RED_CHANNEL & 0xff) * amount) +
((float) (color2 >> RED_CHANNEL & 0xff) * inverseAmount))) & 0xff;
int g = ((int) (((float) (color1 >> GREEN_CHANNEL & 0xff) * amount) +
((float) (color2 >> GREEN_CHANNEL & 0xff) * inverseAmount))) & 0xff;
int b = ((int) (((float) (color1 & 0xff) * amount) +
((float) (color2 & 0xff) * inverseAmount))) & 0xff;
int a = ((int) (((float) (color1 >> ALPHA_CHANNEL & 0xff) * amount) +
((float) (color2 >> ALPHA_CHANNEL & 0xff) * inverseAmount))) & 0xff;
int r = ((int) (((float) (color1 >> RED_CHANNEL & 0xff) * amount) +
((float) (color2 >> RED_CHANNEL & 0xff) * inverseAmount))) & 0xff;
int g = ((int) (((float) (color1 >> GREEN_CHANNEL & 0xff) * amount) +
((float) (color2 >> GREEN_CHANNEL & 0xff) * inverseAmount))) & 0xff;
int b = ((int) (((float) (color1 & 0xff) * amount) +
((float) (color2 & 0xff) * inverseAmount))) & 0xff;
return a << ALPHA_CHANNEL | r << RED_CHANNEL | g << GREEN_CHANNEL | b << BLUE_CHANNEL;
}
return a << ALPHA_CHANNEL | r << RED_CHANNEL | g << GREEN_CHANNEL | b << BLUE_CHANNEL;
}
}

@ -26,35 +26,35 @@ import java.util.TimeZone;
public class DateHelper
{
public static int millisecondsInOneDay = 24 * 60 * 60 * 1000;
public static int millisecondsInOneDay = 24 * 60 * 60 * 1000;
public static long getLocalTime()
{
TimeZone tz = TimeZone.getDefault();
long now = new Date().getTime();
return now + tz.getOffset(now);
}
public static long getLocalTime()
{
TimeZone tz = TimeZone.getDefault();
long now = new Date().getTime();
return now + tz.getOffset(now);
}
public static long getStartOfDay(long timestamp)
{
return (timestamp / millisecondsInOneDay) * millisecondsInOneDay;
}
public static long getStartOfDay(long timestamp)
{
return (timestamp / millisecondsInOneDay) * millisecondsInOneDay;
}
public static long getStartOfToday()
{
return getStartOfDay(DateHelper.getLocalTime());
}
public static long getStartOfToday()
{
return getStartOfDay(DateHelper.getLocalTime());
}
public static String formatTime(Context context, int hours, int minutes)
{
int reminderMilliseconds = (hours * 60 + minutes) * 60 * 1000;
public static String formatTime(Context context, int hours, int minutes)
{
int reminderMilliseconds = (hours * 60 + minutes) * 60 * 1000;
Date date = new Date(reminderMilliseconds);
java.text.DateFormat df = DateFormat.getTimeFormat(context);
df.setTimeZone(TimeZone.getTimeZone("UTC"));
Date date = new Date(reminderMilliseconds);
java.text.DateFormat df = DateFormat.getTimeFormat(context);
df.setTimeZone(TimeZone.getTimeZone("UTC"));
return df.format(date);
}
return df.format(date);
}
// public static Date getStartOfDay(Date date)
// {
@ -67,64 +67,59 @@ public class DateHelper
// return calendar.getTime();
// }
public static int differenceInDays(Date from, Date to)
{
long milliseconds = getStartOfDay(to.getTime()) - getStartOfDay(from.getTime());
public static int differenceInDays(Date from, Date to)
{
long milliseconds = getStartOfDay(to.getTime()) - getStartOfDay(from.getTime());
return (int) (milliseconds / millisecondsInOneDay);
}
public static String differenceInWords(Date from, Date to)
{
Integer days = differenceInDays(from, to);
boolean negative = (days < 0);
days = Math.abs(days);
Integer weeks = (int) Math.round(days / 7.0);
Double months = days / 30.4;
Double years = days / 365.0;
StringBuffer s = new StringBuffer();
DecimalFormat df = new DecimalFormat("#.#");
if(months > 18)
{
s.append(df.format(years));
s.append(" years");
}
else if(weeks > 6)
{
s.append(df.format(months));
s.append(" months");
}
else if(days > 13)
{
s.append(weeks);
s.append(" weeks");
}
else if(days > 6)
{
s.append(days);
s.append(" days");
}
else
{
if(days == 0)
s.append("Today");
else if(days == 1 && negative)
s.append("Yesterday");
else if(days == 1 && !negative)
s.append("Tomorrow");
else
{
if(negative)
s.append("past ");
s.append(new SimpleDateFormat("EEEE").format(to));
}
}
if(negative && days > 6)
s.append(" ago");
return s.toString();
}
}
public static String differenceInWords(Date from, Date to)
{
Integer days = differenceInDays(from, to);
boolean negative = (days < 0);
days = Math.abs(days);
Integer weeks = (int) Math.round(days / 7.0);
Double months = days / 30.4;
Double years = days / 365.0;
StringBuffer s = new StringBuffer();
DecimalFormat df = new DecimalFormat("#.#");
if (months > 18)
{
s.append(df.format(years));
s.append(" years");
}
else if (weeks > 6)
{
s.append(df.format(months));
s.append(" months");
}
else if (days > 13)
{
s.append(weeks);
s.append(" weeks");
}
else if (days > 6)
{
s.append(days);
s.append(" days");
}
else
{
if (days == 0) s.append("Today");
else if (days == 1 && negative) s.append("Yesterday");
else if (days == 1 && !negative) s.append("Tomorrow");
else
{
if (negative) s.append("past ");
s.append(new SimpleDateFormat("EEEE").format(to));
}
}
if (negative && days > 6) s.append(" ago");
return s.toString();
}
}

@ -25,33 +25,33 @@ import android.view.inputmethod.InputMethodManager;
public abstract class DialogHelper
{
// public static AlertDialog alert(Activity context, String title, String message, OnClickListener positiveClickListener) {
// return new AlertDialog.Builder(context)
// .setTitle(title)
// .setMessage(message)
// .setPositiveButton(android.R.string.yes, positiveClickListener)
// .setNegativeButton(android.R.string.no, null).show();
// }
public static abstract class SimpleClickListener implements OnClickListener
{
public abstract void onClick();
public void onClick(DialogInterface dialog, int whichButton)
{
onClick();
}
}
public static interface OnSavedListener
{
public void onSaved(Command command, Object savedObject);
}
public static void showSoftKeyboard(View view)
{
InputMethodManager imm = (InputMethodManager)
view.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
imm.showSoftInput(view, InputMethodManager.SHOW_IMPLICIT);
}
// public static AlertDialog alert(Activity context, String title, String message, OnClickListener positiveClickListener) {
// return new AlertDialog.Builder(context)
// .setTitle(title)
// .setMessage(message)
// .setPositiveButton(android.R.string.yes, positiveClickListener)
// .setNegativeButton(android.R.string.no, null).show();
// }
public static abstract class SimpleClickListener implements OnClickListener
{
public abstract void onClick();
public void onClick(DialogInterface dialog, int whichButton)
{
onClick();
}
}
public static interface OnSavedListener
{
public void onSaved(Command command, Object savedObject);
}
public static void showSoftKeyboard(View view)
{
InputMethodManager imm = (InputMethodManager) view.getContext()
.getSystemService(Context.INPUT_METHOD_SERVICE);
imm.showSoftInput(view, InputMethodManager.SHOW_IMPLICIT);
}
}

@ -81,8 +81,7 @@ abstract public class ReplayableActivity extends Activity
toast.show();
}
public void executeCommand(final Command command, Boolean clearRedoStack,
final Long refreshKey)
public void executeCommand(final Command command, Boolean clearRedoStack, final Long refreshKey)
{
undoList.push(command);

@ -16,7 +16,6 @@
package org.isoron.uhabits;
import android.app.Activity;
import android.graphics.Color;
import android.os.Bundle;
@ -31,7 +30,7 @@ public class IntroActivity extends AppIntro2
showStatusBar(false);
addSlide(AppIntroFragment.newInstance("Welcome",
"Habits Tracker helps you create and maintain good habits.", R.drawable.tutorial_1,
"Loop helps you create and maintain good habits.", R.drawable.tutorial_1,
Color.parseColor("#194673")));
addSlide(AppIntroFragment.newInstance("Create some new habits",

@ -41,8 +41,8 @@ public class MainActivity extends ReplayableActivity
PreferenceManager.setDefaultValues(this, R.xml.preferences, false);
listHabitsFragment = (ListHabitsFragment) getFragmentManager().findFragmentById(
R.id.fragment1);
listHabitsFragment =
(ListHabitsFragment) getFragmentManager().findFragmentById(R.id.fragment1);
ReminderHelper.createReminderAlarms(MainActivity.this);
@ -55,7 +55,7 @@ public class MainActivity extends ReplayableActivity
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
Boolean firstRun = prefs.getBoolean("pref_first_run", true);
if(firstRun)
if (firstRun)
{
SharedPreferences.Editor editor = prefs.edit();
editor.putBoolean("pref_first_run", false);

@ -62,9 +62,9 @@ public class ReminderHelper
alarmIntent.setAction(ReminderAlarmReceiver.ACTION_REMIND);
alarmIntent.setData(uri);
PendingIntent pendingIntent = PendingIntent.getBroadcast(context,
((int) (habit.getId() % Integer.MAX_VALUE)) + 1, alarmIntent,
PendingIntent.FLAG_UPDATE_CURRENT);
PendingIntent pendingIntent =
PendingIntent.getBroadcast(context, ((int) (habit.getId() % Integer.MAX_VALUE)) + 1,
alarmIntent, PendingIntent.FLAG_UPDATE_CURRENT);
AlarmManager manager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
if (Build.VERSION.SDK_INT >= 19)

@ -27,7 +27,8 @@ public class SettingsActivity extends Activity
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
getFragmentManager().beginTransaction().replace(android.R.id.content,
new SettingsFragment()).commit();
getFragmentManager().beginTransaction()
.replace(android.R.id.content, new SettingsFragment())
.commit();
}
}

@ -16,10 +16,6 @@
package org.isoron.uhabits;
import org.isoron.helpers.ReplayableActivity;
import org.isoron.uhabits.models.Habit;
import android.app.Activity;
import android.content.ContentUris;
import android.content.Intent;
import android.graphics.drawable.ColorDrawable;
@ -28,6 +24,9 @@ import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import org.isoron.helpers.ReplayableActivity;
import org.isoron.uhabits.models.Habit;
public class ShowHabitActivity extends ReplayableActivity
{

@ -23,7 +23,6 @@ import android.graphics.ColorMatrix;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.text.format.DateFormat;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
@ -45,270 +44,267 @@ import org.isoron.helpers.DialogHelper.OnSavedListener;
import org.isoron.uhabits.R;
import org.isoron.uhabits.models.Habit;
import java.util.Date;
import java.util.TimeZone;
public class EditHabitFragment extends DialogFragment implements OnClickListener
{
private int mode;
static final int EDIT_MODE = 0;
static final int CREATE_MODE = 1;
private OnSavedListener onSavedListener;
private Habit originalHabit, modified_habit;
private TextView tvName, tvDescription, tvFreqNum, tvFreqDen, tvInputReminder;
private SharedPreferences prefs;
private boolean is24HourMode;
static class SolidColorMatrix extends ColorMatrix
{
public SolidColorMatrix(int color)
{
float matrix[] = { 0.0f, 0.0f, 0.0f, 0.0f, Color.red(color), 0.0f, 0.0f, 0.0f, 0.0f,
Color.green(color), 0.0f, 0.0f, 0.0f, 0.0f, Color.blue(color), 0.0f, 0.0f,
0.0f, 1.0f, 0 };
set(matrix);
}
}
private int mode;
static final int EDIT_MODE = 0;
static final int CREATE_MODE = 1;
private OnSavedListener onSavedListener;
private Habit originalHabit, modified_habit;
private TextView tvName, tvDescription, tvFreqNum, tvFreqDen, tvInputReminder;
private SharedPreferences prefs;
private boolean is24HourMode;
static class SolidColorMatrix extends ColorMatrix
{
public SolidColorMatrix(int color)
{
float matrix[] = {0.0f, 0.0f, 0.0f, 0.0f, Color.red(color), 0.0f, 0.0f, 0.0f, 0.0f,
Color.green(color), 0.0f, 0.0f, 0.0f, 0.0f, Color.blue(color), 0.0f, 0.0f, 0.0f,
1.0f, 0};
set(matrix);
}
}
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
* Factory *
* Factory *
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
static EditHabitFragment editSingleHabitFragment(long id)
{
EditHabitFragment frag = new EditHabitFragment();
Bundle args = new Bundle();
args.putLong("habitId", id);
args.putInt("editMode", EDIT_MODE);
frag.setArguments(args);
return frag;
}
static EditHabitFragment createHabitFragment()
{
EditHabitFragment frag = new EditHabitFragment();
Bundle args = new Bundle();
args.putInt("editMode", CREATE_MODE);
frag.setArguments(args);
return frag;
}
static EditHabitFragment editSingleHabitFragment(long id)
{
EditHabitFragment frag = new EditHabitFragment();
Bundle args = new Bundle();
args.putLong("habitId", id);
args.putInt("editMode", EDIT_MODE);
frag.setArguments(args);
return frag;
}
static EditHabitFragment createHabitFragment()
{
EditHabitFragment frag = new EditHabitFragment();
Bundle args = new Bundle();
args.putInt("editMode", CREATE_MODE);
frag.setArguments(args);
return frag;
}
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
* Creation *
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState)
{
View view = inflater.inflate(R.layout.edit_habit, container, false);
tvName = (TextView) view.findViewById(R.id.input_name);
tvDescription = (TextView) view.findViewById(R.id.input_description);
tvFreqNum = (TextView) view.findViewById(R.id.input_freq_num);
tvFreqDen = (TextView) view.findViewById(R.id.input_freq_den);
tvInputReminder = (TextView) view.findViewById(R.id.input_reminder_time);
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState)
{
View view = inflater.inflate(R.layout.edit_habit, container, false);
tvName = (TextView) view.findViewById(R.id.input_name);
tvDescription = (TextView) view.findViewById(R.id.input_description);
tvFreqNum = (TextView) view.findViewById(R.id.input_freq_num);
tvFreqDen = (TextView) view.findViewById(R.id.input_freq_den);
tvInputReminder = (TextView) view.findViewById(R.id.input_reminder_time);
Button buttonSave = (Button) view.findViewById(R.id.buttonSave);
Button buttonDiscard = (Button) view.findViewById(R.id.buttonDiscard);
Button buttonSave = (Button) view.findViewById(R.id.buttonSave);
Button buttonDiscard = (Button) view.findViewById(R.id.buttonDiscard);
buttonSave.setOnClickListener(this);
buttonDiscard.setOnClickListener(this);
tvInputReminder.setOnClickListener(this);
buttonSave.setOnClickListener(this);
buttonDiscard.setOnClickListener(this);
tvInputReminder.setOnClickListener(this);
ImageButton buttonPickColor = (ImageButton) view.findViewById(R.id.button_pick_color);
ImageButton buttonPickColor = (ImageButton) view.findViewById(R.id.button_pick_color);
prefs = PreferenceManager.getDefaultSharedPreferences(getActivity());
prefs = PreferenceManager.getDefaultSharedPreferences(getActivity());
Bundle args = getArguments();
mode = (Integer) args.get("editMode");
Bundle args = getArguments();
mode = (Integer) args.get("editMode");
is24HourMode = DateFormat.is24HourFormat(getContext());
if(mode == CREATE_MODE)
{
getDialog().setTitle("Create habit");
modified_habit = new Habit();
if (mode == CREATE_MODE)
{
getDialog().setTitle("Create habit");
modified_habit = new Habit();
int defaultNum = prefs.getInt("pref_default_habit_freq_num", modified_habit.freq_num);
int defaultDen = prefs.getInt("pref_default_habit_freq_den", modified_habit.freq_den);
int defaultColor = prefs.getInt("pref_default_habit_color", modified_habit.color);
int defaultNum = prefs.getInt("pref_default_habit_freq_num", modified_habit.freq_num);
int defaultDen = prefs.getInt("pref_default_habit_freq_den", modified_habit.freq_den);
int defaultColor = prefs.getInt("pref_default_habit_color", modified_habit.color);
modified_habit.color = defaultColor;
modified_habit.freq_num = defaultNum;
modified_habit.freq_den = defaultDen;
}
else if (mode == EDIT_MODE)
{
originalHabit = Habit.get((Long) args.get("habitId"));
modified_habit = new Habit(originalHabit);
getDialog().setTitle("Edit habit");
tvName.append(modified_habit.name);
tvDescription.append(modified_habit.description);
}
modified_habit.color = defaultColor;
modified_habit.freq_num = defaultNum;
modified_habit.freq_den = defaultDen;
tvFreqNum.append(modified_habit.freq_num.toString());
tvFreqDen.append(modified_habit.freq_den.toString());
changeColor(modified_habit.color);
updateReminder();
buttonPickColor.setOnClickListener(new OnClickListener()
{
public void onClick(View view)
{
ColorPickerDialog picker =
ColorPickerDialog.newInstance(R.string.color_picker_default_title,
ColorHelper.palette, modified_habit.color, 4,
ColorPickerDialog.SIZE_SMALL);
picker.setOnColorSelectedListener(new ColorPickerSwatch.OnColorSelectedListener()
{
public void onColorSelected(int color)
{
changeColor(color);
}
});
picker.show(getFragmentManager(), "picker");
}
});
return view;
}
private void changeColor(Integer color)
{
modified_habit.color = color;
tvName.setTextColor(color);
SharedPreferences.Editor editor = prefs.edit();
editor.putInt("pref_default_habit_color", color);
editor.apply();
}
private void updateReminder()
{
if (modified_habit.reminder_hour != null)
{
tvInputReminder.setTextColor(Color.BLACK);
tvInputReminder.setText(
DateHelper.formatTime(getActivity(), modified_habit.reminder_hour,
modified_habit.reminder_min));
}
else if(mode == EDIT_MODE)
{
originalHabit = Habit.get((Long) args.get("habitId"));
modified_habit = new Habit(originalHabit);
getDialog().setTitle("Edit habit");
tvName.append(modified_habit.name);
tvDescription.append(modified_habit.description);
}
tvFreqNum.append(modified_habit.freq_num.toString());
tvFreqDen.append(modified_habit.freq_den.toString());
changeColor(modified_habit.color);
updateReminder();
buttonPickColor.setOnClickListener(new OnClickListener()
{
public void onClick(View view)
{
ColorPickerDialog picker = ColorPickerDialog.newInstance(
R.string.color_picker_default_title,
ColorHelper.palette, modified_habit.color, 4, ColorPickerDialog.SIZE_SMALL);
picker.setOnColorSelectedListener(new ColorPickerSwatch.OnColorSelectedListener()
{
public void onColorSelected(int color)
{
changeColor(color);
}
});
picker.show(getFragmentManager(), "picker");
}
});
return view;
}
private void changeColor(Integer color)
{
modified_habit.color = color;
tvName.setTextColor(color);
SharedPreferences.Editor editor = prefs.edit();
editor.putInt("pref_default_habit_color", color);
editor.apply();
}
private void updateReminder()
{
if(modified_habit.reminder_hour != null)
{
tvInputReminder.setTextColor(Color.BLACK);
tvInputReminder.setText(DateHelper.formatTime(getActivity(),
modified_habit.reminder_hour, modified_habit.reminder_min));
}
else
{
tvInputReminder.setTextColor(Color.GRAY);
tvInputReminder.setText("Off");
}
}
public void setOnSavedListener(OnSavedListener onSavedListener)
{
this.onSavedListener = onSavedListener;
}
else
{
tvInputReminder.setTextColor(Color.GRAY);
tvInputReminder.setText("Off");
}
}
public void setOnSavedListener(OnSavedListener onSavedListener)
{
this.onSavedListener = onSavedListener;
}
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
* Callback *
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
@Override
public void onClick(View v)
{
int id = v.getId();
@Override
public void onClick(View v)
{
int id = v.getId();
/* Due date spinner */
if(id == R.id.input_reminder_time)
{
int default_hour = 8;
int default_min = 0;
if(modified_habit.reminder_hour != null) {
default_hour = modified_habit.reminder_hour;
default_min = modified_habit.reminder_min;
}
TimePickerDialog timePicker = TimePickerDialog.newInstance(new OnTimeSetListener()
{
@Override
public void onTimeSet(RadialPickerLayout view, int hour, int minute)
{
modified_habit.reminder_hour = hour;
modified_habit.reminder_min = minute;
updateReminder();
}
@Override
public void onTimeCleared(RadialPickerLayout view)
{
modified_habit.reminder_hour = null;
modified_habit.reminder_min = null;
updateReminder();
}
}, default_hour, default_min, is24HourMode);
timePicker.show(getFragmentManager(), "timePicker");
}
if (id == R.id.input_reminder_time)
{
int default_hour = 8;
int default_min = 0;
if (modified_habit.reminder_hour != null)
{
default_hour = modified_habit.reminder_hour;
default_min = modified_habit.reminder_min;
}
TimePickerDialog timePicker = TimePickerDialog.newInstance(new OnTimeSetListener()
{
@Override
public void onTimeSet(RadialPickerLayout view, int hour, int minute)
{
modified_habit.reminder_hour = hour;
modified_habit.reminder_min = minute;
updateReminder();
}
@Override
public void onTimeCleared(RadialPickerLayout view)
{
modified_habit.reminder_hour = null;
modified_habit.reminder_min = null;
updateReminder();
}
}, default_hour, default_min, is24HourMode);
timePicker.show(getFragmentManager(), "timePicker");
}
/* Save button */
if(id == R.id.buttonSave)
{
Command command = null;
if (id == R.id.buttonSave)
{
Command command = null;
modified_habit.name = tvName.getText().toString().trim();
modified_habit.description = tvDescription.getText().toString().trim();
modified_habit.freq_num = Integer.parseInt(tvFreqNum.getText().toString());
modified_habit.freq_den = Integer.parseInt(tvFreqDen.getText().toString());
modified_habit.name = tvName.getText().toString().trim();
modified_habit.description = tvDescription.getText().toString().trim();
modified_habit.freq_num = Integer.parseInt(tvFreqNum.getText().toString());
modified_habit.freq_den = Integer.parseInt(tvFreqDen.getText().toString());
Boolean valid = true;
Boolean valid = true;
if(modified_habit.name.length() == 0)
{
tvName.setError("Name cannot be blank.");
valid = false;
}
if (modified_habit.name.length() == 0)
{
tvName.setError("Name cannot be blank.");
valid = false;
}
if(modified_habit.freq_den <= 0)
{
tvFreqNum.setError("Number must be positive.");
valid = false;
}
if (modified_habit.freq_den <= 0)
{
tvFreqNum.setError("Number must be positive.");
valid = false;
}
if(modified_habit.freq_num > modified_habit.freq_den)
{
tvFreqNum.setError("You can have at most one repetition per day");
valid = false;
}
if (modified_habit.freq_num > modified_habit.freq_den)
{
tvFreqNum.setError("You can have at most one repetition per day");
valid = false;
}
if(!valid)
return;
if (!valid) return;
SharedPreferences.Editor editor = prefs.edit();
editor.putInt("pref_default_habit_freq_num", modified_habit.freq_num);
editor.putInt("pref_default_habit_freq_den", modified_habit.freq_den);
editor.apply();
SharedPreferences.Editor editor = prefs.edit();
editor.putInt("pref_default_habit_freq_num", modified_habit.freq_num);
editor.putInt("pref_default_habit_freq_den", modified_habit.freq_den);
editor.apply();
Habit savedHabit = null;
Habit savedHabit = null;
if(mode == EDIT_MODE)
{
command = originalHabit.new EditCommand(modified_habit);
savedHabit = originalHabit;
}
if (mode == EDIT_MODE)
{
command = originalHabit.new EditCommand(modified_habit);
savedHabit = originalHabit;
}
if(mode == CREATE_MODE)
command = new Habit.CreateCommand(modified_habit);
if (mode == CREATE_MODE) command = new Habit.CreateCommand(modified_habit);
if(onSavedListener != null)
onSavedListener.onSaved(command, savedHabit);
if (onSavedListener != null) onSavedListener.onSaved(command, savedHabit);
dismiss();
}
dismiss();
}
/* Discard button */
if(id == R.id.buttonDiscard)
{
dismiss();
}
}
if (id == R.id.buttonDiscard)
{
dismiss();
}
}
}

@ -140,8 +140,8 @@ public class ListHabitsFragment extends Fragment
listView.setOnTouchListener(controller);
listView.setDragEnabled(true);
Typeface fontawesome = Typeface.createFromAsset(getActivity().getAssets(),
"fontawesome-webfont.ttf");
Typeface fontawesome =
Typeface.createFromAsset(getActivity().getAssets(), "fontawesome-webfont.ttf");
((TextView) view.findViewById(R.id.tvStarEmpty)).setTypeface(fontawesome);
llEmpty = view.findViewById(R.id.llEmpty);
@ -162,7 +162,7 @@ public class ListHabitsFragment extends Fragment
public void onResume()
{
super.onResume();
if(lastLoadedTimestamp == null || lastLoadedTimestamp != DateHelper.getStartOfToday())
if (lastLoadedTimestamp == null || lastLoadedTimestamp != DateHelper.getStartOfToday())
{
updateHeader();
fetchAllHabits();
@ -192,9 +192,10 @@ public class ListHabitsFragment extends Fragment
{
View check = inflater.inflate(R.layout.list_habits_header_check, null);
Button btCheck = (Button) check.findViewById(R.id.tvCheck);
btCheck.setText(day.getDisplayName(GregorianCalendar.DAY_OF_WEEK,
GregorianCalendar.SHORT, Locale.US) + "\n" +
Integer.toString(day.get(GregorianCalendar.DAY_OF_MONTH)));
btCheck.setText(
day.getDisplayName(GregorianCalendar.DAY_OF_WEEK, GregorianCalendar.SHORT,
Locale.US) + "\n" +
Integer.toString(day.get(GregorianCalendar.DAY_OF_MONTH)));
llButtonsHeader.addView(check);
day.add(GregorianCalendar.DAY_OF_MONTH, -1);
@ -203,7 +204,7 @@ public class ListHabitsFragment extends Fragment
private void fetchAllHabits()
{
if(currentFetchTask != null) currentFetchTask.cancel(true);
if (currentFetchTask != null) currentFetchTask.cancel(true);
currentFetchTask = new AsyncTask<Void, Integer, Void>()
{
@ -219,7 +220,7 @@ public class ListHabitsFragment extends Fragment
long dateFrom = dateTo - (button_count - 1) * DateHelper.millisecondsInOneDay;
int[] empty = new int[button_count];
for(Habit h : newHabits.values())
for (Habit h : newHabits.values())
{
newScores.put(h.getId(), 0);
newPositionToHabit.put(h.position, h);
@ -227,9 +228,9 @@ public class ListHabitsFragment extends Fragment
}
int current = 0;
for(int i = 0; i < newHabits.size(); i++)
for (int i = 0; i < newHabits.size(); i++)
{
if(isCancelled()) return null;
if (isCancelled()) return null;
Habit h = newPositionToHabit.get(i);
newScores.put(h.getId(), h.getScore());
@ -265,7 +266,7 @@ public class ListHabitsFragment extends Fragment
progressBar.setMax(values[1]);
progressBar.setProgress(values[0]);
if(lastLoadedTimestamp == null)
if (lastLoadedTimestamp == null)
{
commit();
adapter.notifyDataSetChanged();
@ -275,7 +276,7 @@ public class ListHabitsFragment extends Fragment
@Override
protected void onPostExecute(Void aVoid)
{
if(isCancelled()) return;
if (isCancelled()) return;
adapter.notifyDataSetChanged();
updateEmptyMessage();
@ -316,7 +317,7 @@ public class ListHabitsFragment extends Fragment
@Override
public void run()
{
if(getStatus() == Status.RUNNING)
if (getStatus() == Status.RUNNING)
{
progressBar.setIndeterminate(true);
progressBar.setVisibility(View.VISIBLE);
@ -353,16 +354,14 @@ public class ListHabitsFragment extends Fragment
AdapterContextMenuInfo info = (AdapterContextMenuInfo) menuInfo;
final Habit habit = habits.get(info.id);
if(habit.isArchived())
menu.findItem(R.id.action_archive_habit).setVisible(false);
else
menu.findItem(R.id.action_unarchive_habit).setVisible(false);
if (habit.isArchived()) menu.findItem(R.id.action_archive_habit).setVisible(false);
else menu.findItem(R.id.action_unarchive_habit).setVisible(false);
}
@Override
public boolean onOptionsItemSelected(MenuItem item)
{
switch(item.getItemId())
switch (item.getItemId())
{
case R.id.action_add:
{
@ -427,7 +426,7 @@ public class ListHabitsFragment extends Fragment
{
Habit h = (Habit) savedObject;
if(h == null) activity.executeCommand(command, null);
if (h == null) activity.executeCommand(command, null);
else activity.executeCommand(command, h.getId());
adapter.notifyDataSetChanged();
@ -436,24 +435,23 @@ public class ListHabitsFragment extends Fragment
private void updateEmptyMessage()
{
if(lastLoadedTimestamp == null)
llEmpty.setVisibility(View.GONE);
else
llEmpty.setVisibility(habits.size() > 0 ? View.GONE : View.VISIBLE);
if (lastLoadedTimestamp == null) llEmpty.setVisibility(View.GONE);
else llEmpty.setVisibility(habits.size() > 0 ? View.GONE : View.VISIBLE);
}
@Override
public boolean onLongClick(View v)
{
switch(v.getId())
switch (v.getId())
{
case R.id.tvCheck:
{
lastLongClick = new Date().getTime();
if(!short_toggle_enabled)
if (!short_toggle_enabled)
{
toggleCheck(v);
Vibrator vb = (Vibrator) getActivity().getSystemService(Context.VIBRATOR_SERVICE);
Vibrator vb =
(Vibrator) getActivity().getSystemService(Context.VIBRATOR_SERVICE);
vb.vibrate(100);
}
@ -472,10 +470,8 @@ public class ListHabitsFragment extends Fragment
long timestamp = DateHelper.getStartOfDay(
DateHelper.getLocalTime() - offset * DateHelper.millisecondsInOneDay);
if(v.getTag(R.string.toggle_key).equals(2))
updateCheck(habit.color, (TextView) v, 0);
else
updateCheck(habit.color, (TextView) v, 2);
if (v.getTag(R.string.toggle_key).equals(2)) updateCheck(habit.color, (TextView) v, 0);
else updateCheck(habit.color, (TextView) v, 2);
executeCommand(habit.new ToggleRepetitionCommand(timestamp), habit.getId());
}
@ -500,13 +496,11 @@ public class ListHabitsFragment extends Fragment
@Override
public void onClick(View v)
{
switch(v.getId())
switch (v.getId())
{
case R.id.tvCheck:
if(short_toggle_enabled)
toggleCheck(v);
else
activity.showToast(R.string.long_press_to_toggle);
if (short_toggle_enabled) toggleCheck(v);
else activity.showToast(R.string.long_press_to_toggle);
return;
}
}
@ -548,14 +542,14 @@ public class ListHabitsFragment extends Fragment
{
final Habit habit = positionToHabit.get(position);
if (view == null || (Long) view.getTag(R.id.KEY_TIMESTAMP) !=
DateHelper.getStartOfToday())
if (view == null ||
(Long) view.getTag(R.id.KEY_TIMESTAMP) != DateHelper.getStartOfToday())
{
view = inflater.inflate(R.layout.list_habits_item, null);
((TextView) view.findViewById(R.id.tvStar)).setTypeface(fontawesome);
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(tvNameWidth,
LayoutParams.WRAP_CONTENT, 1);
LinearLayout.LayoutParams params =
new LinearLayout.LayoutParams(tvNameWidth, LayoutParams.WRAP_CONTENT, 1);
view.findViewById(R.id.tvName).setLayoutParams(params);
Display display = ((WindowManager) context.getSystemService(Context.WINDOW_SERVICE))
@ -593,7 +587,7 @@ public class ListHabitsFragment extends Fragment
tvName.setText(habit.name);
tvName.setTextColor(activeColor);
if(habit.isArchived())
if (habit.isArchived())
{
activeColor = ColorHelper.palette[12];
tvName.setTextColor(activeColor);
@ -666,7 +660,7 @@ public class ListHabitsFragment extends Fragment
public void onPostExecuteCommand(Long refreshKey)
{
if(refreshKey == null) fetchAllHabits();
if (refreshKey == null) fetchAllHabits();
else fetchHabit(refreshKey);
}
}

@ -23,7 +23,8 @@ import android.preference.PreferenceFragment;
import org.isoron.uhabits.R;
public class SettingsFragment extends PreferenceFragment implements SharedPreferences.OnSharedPreferenceChangeListener
public class SettingsFragment extends PreferenceFragment
implements SharedPreferences.OnSharedPreferenceChangeListener
{
@Override
public void onCreate(Bundle savedInstanceState)

@ -80,9 +80,9 @@ public class ShowHabitFragment extends Fragment implements DialogHelper.OnSavedL
tvStreaks.setTextColor(habit.color);
LinearLayout llOverview = (LinearLayout) view.findViewById(R.id.llOverview);
llOverview.addView(new RingView(activity, (int) activity.getResources().getDimension(
R.dimen.small_square_size) * 4, habit.color,
((float) habit.getScore() / Habit.MAX_SCORE), "Habit strength"));
llOverview.addView(new RingView(activity,
(int) activity.getResources().getDimension(R.dimen.small_square_size) * 4,
habit.color, ((float) habit.getScore() / Habit.MAX_SCORE), "Habit strength"));
LinearLayout llStrength = (LinearLayout) view.findViewById(R.id.llStrength);
llStrength.addView(new HabitScoreView(activity, habit,
@ -130,7 +130,7 @@ public class ShowHabitFragment extends Fragment implements DialogHelper.OnSavedL
{
Habit h = (Habit) savedObject;
if(h == null) activity.executeCommand(command, null);
if (h == null) activity.executeCommand(command, null);
else activity.executeCommand(command, h.getId());
ReminderHelper.createReminderAlarms(activity);

@ -105,7 +105,7 @@ public class Habit extends Model
List<Habit> habits = select().execute();
HashMap<Long, Habit> map = new HashMap<>();
for(Habit h : habits)
for (Habit h : habits)
{
map.put(h.getId(), h);
}
@ -121,10 +121,8 @@ public class Habit extends Model
protected static From select()
{
if(includeArchived)
return new Select().from(Habit.class).orderBy("position");
else
return new Select().from(Habit.class).where("archived = 0").orderBy("position");
if (includeArchived) return new Select().from(Habit.class).orderBy("position");
else return new Select().from(Habit.class).where("archived = 0").orderBy("position");
}
public static void setIncludeArchived(boolean includeArchived)
@ -155,7 +153,8 @@ public class Habit extends Model
public static java.util.List<Habit> getHighlightedHabits()
{
return select().where("highlight = 1").orderBy("reminder_hour desc, reminder_min desc")
return select().where("highlight = 1")
.orderBy("reminder_hour desc, reminder_min desc")
.execute();
}
@ -170,9 +169,11 @@ public class Habit extends Model
Habit h = Habit.getByPosition(from);
if (to < from) new Update(Habit.class).set("position = position + 1")
.where("position >= ? and position < ?", to, from).execute();
.where("position >= ? and position < ?", to, from)
.execute();
else new Update(Habit.class).set("position = position - 1")
.where("position > ? and position <= ?", from, to).execute();
.where("position > ? and position <= ?", from, to)
.execute();
h.position = to;
h.save();
@ -193,8 +194,7 @@ public class Habit extends Model
}
ActiveAndroid.setTransactionSuccessful();
}
finally
} finally
{
ActiveAndroid.endTransaction();
}
@ -271,8 +271,10 @@ public class Habit extends Model
public void deleteReps(long timestamp)
{
new Delete().from(Repetition.class).where("habit = ?", getId())
.and("timestamp = ?", timestamp).execute();
new Delete().from(Repetition.class)
.where("habit = ?", getId())
.and("timestamp = ?", timestamp)
.execute();
}
public void deleteCheckmarksNewerThan(long timestamp)
@ -306,7 +308,7 @@ public class Habit extends Model
int nDays = (int) ((toTimestamp - fromTimestamp) / day) + 1;
int[] checks = new int[nDays];
if(cursor.moveToFirst())
if (cursor.moveToFirst())
{
do
{
@ -327,7 +329,7 @@ public class Habit extends Model
long day = DateHelper.millisecondsInOneDay;
Checkmark newestCheckmark = getNewestCheckmark();
if(newestCheckmark == null)
if (newestCheckmark == null)
{
Repetition oldestRep = getOldestRep();
if (oldestRep == null) return;
@ -339,8 +341,7 @@ public class Habit extends Model
beginning = newestCheckmark.timestamp + day;
}
if(beginning > today)
return;
if (beginning > today) return;
long beginningExtended = beginning - (long) (freq_den) * day;
List<Repetition> reps = selectRepsFromTo(beginningExtended, today).execute();
@ -382,8 +383,7 @@ public class Habit extends Model
}
ActiveAndroid.setTransactionSuccessful();
}
finally
} finally
{
ActiveAndroid.endTransaction();
}
@ -419,10 +419,7 @@ public class Habit extends Model
public Repetition getOldestRepNewerThan(long timestamp)
{
return selectReps()
.where("timestamp > ?", timestamp)
.limit(1)
.executeSingle();
return selectReps().where("timestamp > ?", timestamp).limit(1).executeSingle();
}
public void toggleRepetition(long timestamp)
@ -471,13 +468,18 @@ public class Habit extends Model
public Score getNewestScore()
{
return new Select().from(Score.class).where("habit = ?", getId()).orderBy("timestamp desc")
.limit(1).executeSingle();
return new Select().from(Score.class)
.where("habit = ?", getId())
.orderBy("timestamp desc")
.limit(1)
.executeSingle();
}
public void deleteScoresNewerThan(long timestamp)
{
new Delete().from(Score.class).where("habit = ?", getId()).and("timestamp >= ?", timestamp)
new Delete().from(Score.class)
.where("habit = ?", getId())
.and("timestamp >= ?", timestamp)
.execute();
}
@ -533,8 +535,7 @@ public class Habit extends Model
}
ActiveAndroid.setTransactionSuccessful();
}
finally
} finally
{
ActiveAndroid.endTransaction();
}
@ -549,17 +550,18 @@ public class Habit extends Model
public List<Score> getScores(long fromTimestamp, long toTimestamp, int divisor, long offset)
{
return new Select().from(Score.class).where("habit = ? and timestamp > ? and " +
"timestamp <= ? and (timestamp - ?) % ? = 0", getId(), fromTimestamp, toTimestamp,
offset, divisor).execute();
return new Select().from(Score.class)
.where("habit = ? and timestamp > ? and " +
"timestamp <= ? and (timestamp - ?) % ? = 0", getId(), fromTimestamp,
toTimestamp, offset, divisor)
.execute();
}
public List<Streak> getStreaks()
{
updateStreaks();
return new Select()
.from(Streak.class)
return new Select().from(Streak.class)
.where("habit = ?", getId())
.orderBy("end asc")
.execute();
@ -567,8 +569,7 @@ public class Habit extends Model
public Streak getNewestStreak()
{
return new Select()
.from(Streak.class)
return new Select().from(Streak.class)
.where("habit = ?", getId())
.orderBy("end desc")
.limit(1)
@ -582,7 +583,7 @@ public class Habit extends Model
long day = DateHelper.millisecondsInOneDay;
Streak newestStreak = getNewestStreak();
if(newestStreak == null)
if (newestStreak == null)
{
Repetition oldestRep = getOldestRep();
if (oldestRep == null) return;
@ -597,7 +598,7 @@ public class Habit extends Model
beginning = oldestRep.timestamp;
}
if(beginning > today) return;
if (beginning > today) return;
int checks[] = getCheckmarks(beginning, today);
ArrayList<Long> list = new ArrayList<>();
@ -605,17 +606,16 @@ public class Habit extends Model
long current = beginning;
list.add(current);
for(int i = 1; i < checks.length; i++)
for (int i = 1; i < checks.length; i++)
{
current += day;
int j = checks.length - i - 1;
if((checks[j + 1] == 0 && checks[j] > 0)) list.add(current);
if((checks[j + 1] > 0 && checks[j] == 0)) list.add(current - day);
if ((checks[j + 1] == 0 && checks[j] > 0)) list.add(current);
if ((checks[j + 1] > 0 && checks[j] == 0)) list.add(current - day);
}
if(list.size() % 2 == 1)
list.add(current);
if (list.size() % 2 == 1) list.add(current);
ActiveAndroid.beginTransaction();
@ -632,8 +632,7 @@ public class Habit extends Model
}
ActiveAndroid.setTransactionSuccessful();
}
finally
} finally
{
ActiveAndroid.endTransaction();
}
@ -657,7 +656,8 @@ public class Habit extends Model
{
savedHabit.save();
savedId = savedHabit.getId();
} else
}
else
{
savedHabit.save(savedId);
}

@ -21,11 +21,12 @@ import com.activeandroid.annotation.Column;
import com.activeandroid.annotation.Table;
@Table(name = "Repetitions")
public class Repetition extends Model {
public class Repetition extends Model
{
@Column(name = "habit")
public Habit habit;
@Column(name = "habit")
public Habit habit;
@Column(name = "timestamp")
public Long timestamp;
@Column(name = "timestamp")
public Long timestamp;
}

@ -23,12 +23,12 @@ import com.activeandroid.annotation.Table;
@Table(name = "Score")
public class Score extends Model
{
@Column(name = "habit")
public Habit habit;
@Column(name = "habit")
public Habit habit;
@Column(name = "timestamp")
public Long timestamp;
@Column(name = "timestamp")
public Long timestamp;
@Column(name = "score")
public Integer score;
@Column(name = "score")
public Integer score;
}

@ -29,13 +29,11 @@ import android.view.View;
import org.isoron.helpers.ColorHelper;
import org.isoron.helpers.DateHelper;
import org.isoron.uhabits.R;
import org.isoron.uhabits.models.Checkmark;
import org.isoron.uhabits.models.Habit;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.GregorianCalendar;
import java.util.List;
public class HabitHistoryView extends View
{
@ -122,7 +120,7 @@ public class HabitHistoryView extends View
Rect square = new Rect(0, 0, squareSize - squareSpacing, squareSize - squareSpacing);
Calendar currentDate = new GregorianCalendar();
currentDate.add(Calendar.DAY_OF_YEAR, - (offsetWeeks - 1) * 7);
currentDate.add(Calendar.DAY_OF_YEAR, -(offsetWeeks - 1) * 7);
int nDays = nColumns * 7;
int todayWeekday = new GregorianCalendar().get(Calendar.DAY_OF_WEEK) % 7;
@ -160,12 +158,14 @@ public class HabitHistoryView extends View
pTextHeader);
previousMonth = month;
justPrintedYear = false;
} else if (!year.equals(previousYear))
}
else if (!year.equals(previousYear))
{
canvas.drawText(year, square.left, square.bottom - headerTextOffset, pTextHeader);
previousYear = year;
justPrintedYear = true;
} else
}
else
{
justPrintedYear = false;
}
@ -177,7 +177,7 @@ public class HabitHistoryView extends View
{
if (!(i == nColumns - 1 && offsetWeeks == 0 && j > todayWeekday))
{
if(k >= checks.length) pSquareBg.setColor(colors[0]);
if (k >= checks.length) pSquareBg.setColor(colors[0]);
else pSquareBg.setColor(colors[checks[k]]);
canvas.drawRect(square, pSquareBg);
@ -225,7 +225,7 @@ public class HabitHistoryView extends View
if (Math.abs(dy) > Math.abs(dx)) return false;
getParent().requestDisallowInterceptTouchEvent(true);
if(move(dx))
if (move(dx))
{
prevX = x;
prevY = y;
@ -247,7 +247,6 @@ public class HabitHistoryView extends View
invalidate();
return true;
}
else
return false;
else return false;
}
}

@ -98,8 +98,8 @@ public class HabitScoreView extends View
for (int i = 0; i < nColumns * BUCKET_SIZE; i++)
fromTimestamp -= DateHelper.millisecondsInOneDay;
scores = habit.getScores(fromTimestamp, toTimestamp, BUCKET_SIZE * DateHelper.millisecondsInOneDay,
toTimestamp);
scores = habit.getScores(fromTimestamp, toTimestamp,
BUCKET_SIZE * DateHelper.millisecondsInOneDay, toTimestamp);
}
@Override
@ -167,7 +167,8 @@ public class HabitScoreView extends View
if (!month.equals(previousMonth))
{
canvas.drawText(month, r.centerX(), r.bottom + lineHeight * 1.2f, pText);
} else
}
else
{
canvas.drawText(day, r.centerX(), r.bottom + lineHeight * 1.2f, pText);
}
@ -263,6 +264,7 @@ public class HabitScoreView extends View
fetchScores();
invalidate();
return true;
} else return false;
}
else return false;
}
}

@ -26,7 +26,6 @@ import android.view.MotionEvent;
import android.view.View;
import org.isoron.helpers.ColorHelper;
import org.isoron.helpers.DateHelper;
import org.isoron.uhabits.models.Habit;
import org.isoron.uhabits.models.Streak;
@ -84,7 +83,7 @@ public class HabitStreakView extends View
{
streaks = habit.getStreaks();
for(Streak s : streaks)
for (Streak s : streaks)
maxStreakLength = Math.max(maxStreakLength, s.length);
}
@ -92,7 +91,7 @@ public class HabitStreakView extends View
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec)
{
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
setMeasuredDimension(getMeasuredWidth(), columnHeight + 2*barHeaderHeight);
setMeasuredDimension(getMeasuredWidth(), columnHeight + 2 * barHeaderHeight);
}
@Override
@ -116,23 +115,23 @@ public class HabitStreakView extends View
String previousMonth = "";
for (int offset = 0; offset < nColumns && start+offset < nStreaks; offset++)
for (int offset = 0; offset < nColumns && start + offset < nStreaks; offset++)
{
String month = dfMonth.format(streaks.get(start+offset).start);
String month = dfMonth.format(streaks.get(start + offset).start);
long l = streaks.get(offset+start).length;
long l = streaks.get(offset + start).length;
double lRelative = ((double) l) / maxStreakLength;
pBar.setColor(colors[(int) Math.floor(lRelative*3)]);
pBar.setColor(colors[(int) Math.floor(lRelative * 3)]);
int height = (int) (columnHeight * lRelative);
Rect r = new Rect(0,0,columnWidth-2, height);
Rect r = new Rect(0, 0, columnWidth - 2, height);
r.offset(offset * columnWidth, barHeaderHeight + columnHeight - height);
canvas.drawRect(r, pBar);
canvas.drawText(Long.toString(l), r.centerX(), r.top - barHeaderOffset, pBar);
if(!month.equals(previousMonth))
if (!month.equals(previousMonth))
canvas.drawText(month, r.centerX(), r.bottom + lineHeight * 1.2f, pText);
previousMonth = month;
@ -161,7 +160,7 @@ public class HabitStreakView extends View
if (Math.abs(dy) > Math.abs(dx)) return false;
getParent().requestDisallowInterceptTouchEvent(true);
if(move(dx))
if (move(dx))
{
prevX = x;
prevY = y;
@ -182,7 +181,6 @@ public class HabitStreakView extends View
invalidate();
return true;
}
else
return false;
else return false;
}
}

@ -52,7 +52,7 @@ public class RingView extends View
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec)
{
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
setMeasuredDimension(size, size + (int) (2*lineHeight));
setMeasuredDimension(size, size + (int) (2 * lineHeight));
}
@Override
@ -75,9 +75,10 @@ public class RingView extends View
pRing.setColor(Color.GRAY);
pRing.setTextSize(size * 0.2f);
lineHeight = pRing.getFontSpacing();
canvas.drawText(String.format("%.0f%%", perc * 100), r.centerX(), r.centerY()+lineHeight/3, pRing);
canvas.drawText(String.format("%.0f%%", perc * 100), r.centerX(),
r.centerY() + lineHeight / 3, pRing);
pRing.setTextSize(size * 0.15f);
canvas.drawText(label, size/2, size + lineHeight * 1.2f, pRing);
canvas.drawText(label, size / 2, size + lineHeight * 1.2f, pRing);
}
}

Loading…
Cancel
Save